查找添加动态添加的TableRow

时间:2019-03-01 21:05:55

标签: javascript jquery

我正在尝试查找表行,这些表行是动态创建的行,例如,警报中显示的第一行索引以及单击时提供的click事件。但是,当我在动态添加的第一行之后单击任何其他行时,它又变回空白。

最终,我想在与行相关的文本框中获取值。首先,我只是尝试查找该行,然后,我将转到文本框。

HTML

 <table class="table table-bordered table-framed" id="seconDTableAdd" style="display:block;height: 100%;">
                 <tbody>
                        <tr class="AddBookmarksMenuHere">
                                <td style="width: 80%;">
                                    <input type='text' id="txtTitle" name="txtTitle[]" style=" width: 300px; padding - top: 1px; height: 20px; font - size: 10px;  color: #555555; vertical - align: left; background - color: #ffffff;1px solid #cccccc;border - radius: 1px; " />
                                    <input type="hidden" name="parentType" id="parentType">
                                    <input type="hidden" name="ChildRank" id="parentType">
                                </td>
                                <td style="width: 20%;"><a onclick="AddRow()">+</a></td>
                          </tr>
                 </tbody>
  </table>

添加行功能

function AddRow() {
    var i = 2;

    var data = "<tr class='AddBookmarksMenuHere'><td style='width:80%;'><input type='text' id='txtTitle" + i + "' name='txtTitle[]' style = ' width: 300px; padding - top: 1px; height: 20px; font - size: 10px;  color: #555555; vertical - align: left; background - color: #ffffff;1px solid #cccccc;border - radius: 1px; '/></td>";
        data += "   <td style='width:20%;'><a class='RemoveThisRow' id='remCF" + i + "' onclick='RemoveRow(" + i + ")'>---</a></td></tr>";
  $('table').append(data);
    i++;
}

找到“ TableRow”

$('#seconDTableAdd').find('tr').click(function () {
     alert('You clicked row ' + ($(this).index() + 1));
});

2 个答案:

答案 0 :(得分:2)

我认为,您正在寻找委托语法的jQuery。

$('#seconDTableAdd').on('click', 'tr', function(e) {
    alert('You clicked row ' + ($(this).index() + 1));
});

您的代码仅将click事件关联到调用该函数时可用的所有行。任何动态添加的行都不会附加事件。而是,事件委托将整个表上的单击处理程序连接起来。每当单击时,都会检查单击是否发生在与第二个参数(在您的情况下为'tr')中给定选择器匹配的元素上。仅当选择器与源匹配时,它才会执行事件。

答案 1 :(得分:0)

您想要的是将功能绑定到元素。通过动态创建,您仍然可以在添加之前绑定到DOM中已经存在的元素,然后使用所需的选择器在其子元素中查找。使用jQuery:

$(‘#someId’).on(‘click’, ‘someSelector’, function () { });