首页 > 解决方案 > 将 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);

            }

标签: javascript

解决方案


您的代码存在一些问题。这个应该修。我添加了很多评论。随意询问是否有任何不清楚的地方。

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();
     }
}

推荐阅读