我有一个带有单元格的表格,可以在其中输入值(该表是一个时间表,通过双击这个单元格,我可以在单元格内输入房间号)。现在,我想在选项卡键上添加一个键侦听器。如果按下选项卡键,将保存当前单元格中的值,并将下一个单元格(右转到当前单元格)转换为输入字段。但是,如果我按下选项卡键,值将得到保存(如我所愿),下一个单元格将转换为输入字段(如我所愿),但只需停留一毫秒,然后它就消失了,我不知道为什么。
有关更多代码,请询问
以下是代码:
//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);
}发布于 2019-12-09 14:09:02
问题是getData-函数(也就是ajax调用)在调用toInput-函数之后完成并构建了表。因此,输入字段将被添加,旧表(在添加输入字段之前)将再次重建。
function toInput(cell){
var input = document.createElement('input');
input.value = cell.innerHTML;
setTimeout(function() { input.focus(); }, 200);
cell.appendChild(input);
window.addEventListener('keydown', function(e){
if(e.keyCode == '13'){
var text = input.value;
cell.innerHTML = text;
getData("get"+getString(cell.parentNode.cells[0].childNodes[0].innerHTML));
}else if(e.keyCode == '9'){
var text = input.value;
cell.innerHTML = text;
//getData("get"+getString(cell.parentNode.cells[0].childNodes[0].innerHTML));
toInput(cell.nextSibling);
}
}, true);
}发布于 2019-12-09 14:02:21
您的代码有一些问题。这个应该能修好。我加了很多评论。如果有什么不清楚的地方,可以随便问一下。
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();
}
}https://stackoverflow.com/questions/59250254
复制相似问题