按创建表行 输入 键

Create table row on pressing Enter Key

本文关键字:输入 创建      更新时间:2023-09-26

我正在动态创建一个html表。在这里,对于每一行,递归调用创建两列。简单地说,当单击第二个框时,将创建一个新行,依此类推。但是我想用"Enter"按键替换单击。我试过了,代码可以通过单击创建新行,但不能通过按 Enter 键。

  function CreateRow(){
    // Find a <table> element with id="myTable":
    var table = document.getElementById("myTable");
    // Create an empty <tr> element and add it to the 1st position of the table:
    var row = table.insertRow();
    // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
/**    $(cell2).bind('click', function() {
        CreateRow();
    });
 */
$(cell2).keydown(function (e){
    if(e.keyCode == 13){
        CreateRow();
    }
});

    // Add some text to the new cells:
    cell1.innerHTML = "NEW CELL1";
    cell2.innerHTML = "NEW CELL2";
}

请帮忙。

不要将 keydown 事件绑定到表单元格,而是将其绑定到文档。

$(document).keydown(function (e) {