按Enter键创建表格行

时间:2015-01-23 19:50:37

标签: javascript jquery html dom

我正在动态创建一个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";

}

请帮忙。

1 个答案:

答案 0 :(得分:4)

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

$(document).keydown(function (e) {
相关问题