javascript - 将 nextSibling 转换为 Input
问题描述
我有一个带有单元格的表格,我可以在其中输入值(表格是一个时间表,我可以通过双击该单元格在单元格内输入房间号)。现在我想在 tab 键上添加一个键监听器。如果我按 Tab 键,则应保存当前单元格中的值,并且下一个单元格(当前单元格的右侧)将转换为输入字段。但是,如果我按下制表键,值会被保存(如我所愿),下一个单元格将转换为输入字段(如我所愿),但只需在那里停留一毫秒,然后它就会消失,我不知道为什么
更多代码请询问
这是代码:
//the cell which get double-clicked
function toInput(cell){
var input = document.createElement('input');
input.value = cell.innerHTML;
setTimeout(function() { input.focus(); }, 200);
cell.appendChild(input);
alert("toInput");
window.addEventListener('keydown', function(e){
if(e.keyCode == '13'){
var text = input.value;
cell.innerHTML = text;
//the function which send the data to the backend
getData("get"+getString(cell.parentNode.cells[0].childNodes[0].innerHTML));
}else if(e.keyCode == '9'){
alert("tab");
var text = input.value;
cell.innerHTML = text;
getData("get"+getString(cell.parentNode.cells[0].childNodes[0].innerHTML));
toInput(cell.nextSibling);
}
}, false);
}
解决方案
您的代码存在一些问题。这个应该修。我添加了很多评论。随意询问是否有任何不清楚的地方。
function toInput(cell){
// use let (limits the scope of the variable to current function)
let input = document.createElement('input');
// read content and place it in your input
input.value = cell.innerHTML;
// clear HTML content of cell, now that we read its value
cell.innerHTML = '';
// append input in empty cell
cell.appendChild(input);
// focus on input which exists
input.focus();
// add a listener on this input
input.addEventListener('keydown', function(e){
// ENTER key or TAB key (common code)
if(e.keyCode == '13' || e.keyCode == '9'){
// remove current element + its handlers and update cell value
cell.innerHTML = input.value;
// the function which send the data to the backend
// the last function is a callback function (executes at the end of something asynchronous, like AJAX)
getData("get"+getString(cell.parentNode.cells[0].childNodes[0].innerHTML), function(){
// only for TAB key, convert next CELL to INPUT
if(e.keyCode == '9'){
toInput(cell.nextSibling);
}
});
}
}, false);
}
function getData(your_parameter, callback){
// your code ...
// inside ajax success loop, at the end add this:
if (typeof callback == 'function'){
// if the callback parameter is a function, execute it
callback();
}
}
推荐阅读
- python - tensorflow惰性执行模式下for循环的实现
- sql - 如何在不使用 Exists 关键字的情况下编写等效查询,以便将其转换为关系代数?
- java - 使用 Intellij 时在 macOS 扩展坞上隐藏 Gradle 守护程序的 Java 图标?
- git - VSCode 缺少源代码控制图标
- c++ - 有没有更快的方法来逐位连接两个整数?
- reactjs - React - 无法在单个 useEffect 中正确更新状态
- gdb - 如何设置确切的指令“gdb”设置断点?
- r - 如果 R 中两个条件的总和小于 X,则删除数据行
- sql - 为列的每个值选择最小 num
- python - 使用 BeautifulSoup 从网页列表中抓取链接