gpt4 book ai didi

javascript - 将 nextSibling 转换为输入

转载 作者:行者123 更新时间:2023-11-30 19:03:25 25 4
gpt4 key购买 nike

我有一个包含单元格的表格,我可以在其中输入值(该表格是一个时间表,我可以通过双击该单元格在单元格中输入房间号)。现在我想在 tab 键上添加一个键监听器。如果我按下 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();
}
}

关于javascript - 将 nextSibling 转换为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59250254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com