javascript - 按 Enter 键创建表格行

标签 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";

}

请帮忙。

最佳答案

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

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

关于javascript - 按 Enter 键创建表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28117639/

相关文章:

javascript - 从 jquery 动画中排除元素

javascript - 我的动画 jQuery 不透明度不起作用

php - 使用 Bootstrap 版本 3.1,输入光标和文本未出现在输入字段中

html - CSS:背景过滤器的解决方法?

javascript - 如何获取数组中的对象值

html - UL list - 不同颜色的元素符号

php - 如何将我的应用程序限制为单个浏览器选项卡?

javascript - 尝试让 .modal ('show' )从右侧而不是顶部滑动元素

javascript - 如何使用脚本执行自动单击jsf中的命令按钮

JavaScript 表单验证而不发出警报