简体   繁体   English

动态插入的表:JQuery未检测到最后一行

[英]Dynamically inserted table: last row not detected by JQuery

I'm using JQuery for creating dynamic table row based on user insertion. 我正在使用JQuery基于用户插入来创建动态表行。

My HTML: 我的HTML:

     <table id="list">
            <thead>
              <tr>
                <th>first header</th>
                <th>second header</th>
                <th>third header</th>
              </tr>
            </thead>
             <tbody>
               <tr>
                 <td><input type="text" name="first" /></td>
                 <td><input type="text" name="second" id="second" /></td>
                 <td><button class="alert hollow button" href="#">X</button>                 </td>
               </tr>
             </tbody>
     </table>

And JavaScript: 和JavaScript:

$('#list tr:last td:nth-last-child(2) input[name=second]').keyup(function (event) {

    if ($(this).val().length > 4 && $('#list tr:last td:nth-last-child(2) input[name=second]').val().length > 4) {
        $('#list tbody').append('<tr>
                     <td><input type="text" name="first" /></td>
                     <td><input type="text" name="second" id="second" /></td>
                     <td><button class="alert hollow button" href="#">X</button></td>
                   </tr>');
    }
});

The above code only works for the first row and the inserted row has no JS code-behind. 上面的代码仅适用于第一行,插入的行后面没有JS代码。

You haven't given complete code, but i suspect this is your issue.. 您尚未提供完整的代码,但我怀疑这是您的问题。

Replace this 取代这个

$('#list tr:last td:nth-last-child(2) input[name=second]').keyup(function (event)

with this 有了这个

$('#list').on('keyup', 'tr:last td:nth-last-child(2) input[name=second]', function (event)

You are probably not using proper event delegation, and you're trying to bind a keyup event on an element that doesn't exist yet (you say the rows are added dynamically). 您可能未使用适当的事件委托,并且试图将keyup事件绑定到尚不存在的元素上(您说这些行是动态添加的)。 Instead we bind the keyup to the table that is part of the initial document, and say what happends when a child that meets X criteria has a keyup event fired 相反,我们将keyup绑定到作为初始文档一部分的表,并说当满足X准则的孩子触发了keyup事件时会发生什么

您的函数不绑定不上的页面加载存在的元素,使用on动态生成的元素

$(document).on('keyup', '#list tr:last td:nth-last-child(2) input[name=second]', function (event) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM