使用无法定位的JQuery在HTML表中动态插入行

时间:2017-07-17 12:33:30

标签: javascript jquery dom html-table nodes

我无法通过使用下面的代码点击“Enter”来定位新创建的行。如果我感到如此倾向,我想继续按“Enter”创建新行;但是,按两次输入将只产生一个新行(来自原始HTML行)。为了调试这种情况,我使用了一个click事件监听器来控制与该表关联的节点的日志记录,并发现奇怪的是在本机HTML的每一行之间都有文本节点;但是,每个新行都不会动态生成这些文本节点。 HTML表格是否需要这些文本节点才能正常运行?

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8;charset=utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $( document ).ready(function() {
            $("tr").on("keydown", "input", function(){
                keyDownLocation = this.selectionStart;
            });

            $("tr").on("keyup", "input", function(e){
                if (e.key === "Enter") {
                    var tempSelect = this.value.substr(this.selectionStart);
                    this.value = this.value.substr(0, this.selectionStart);
                    $(this).parent().parent().after('<tr><td class="checkbox-td"><input type="checkbox" name="checklist-list" class="checkbox-box"></td><td class="item-td"><input class="input-item" type="text" value="' + tempSelect + '"></td></tr>');
                    $(this).parent().parent().next().find(".input-item").focus();
                }
            });

            $("tr").on("click", "input", function(){
                console.log($(this));
                console.log($(this).parent().parent().parent()[0].childNodes);
            });
        });
    </script>
    <title>Title</title>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th><input type="checkbox" name="checklist-list" class="checkbox-box"></th>
                <th>Item</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td class="checkbox-td"><input type="checkbox" name="checklist-list" class="checkbox-box"></td>
                <td class="item-td"><input class="input-item" type="text" value="Artificial"></td>
            </tr>
            <tr>
                <td class="checkbox-td"><input type="checkbox" name="checklist-list" class="checkbox-box"></td>
                <td class="item-td"><input class="input-item" type="text" value="Broken"></td>
            </tr>
            <tr>
                <td class="checkbox-td"><input type="checkbox" name="checklist-list" class="checkbox-box"></td>
                <td class="item-td"><input class="input-item" type="text" value="Casual"></td>
            </tr>
        </tbody>
        <tfoot>
        </tfoot>
    </table>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

他们是,你的代表选择器是错误的。您插入的tr与DOM准备好的其他人一样没有绑定...所以将其绑定到已经存在的tbody,然后查找tr

$("tbody").on("keydown", "tr input", function(){


$("tbody").on("keyup", "tr input", function(e){


$("tbody").on("click", "tr input", function(){

演示:https://jsfiddle.net/ooavyybm/