【问题标题】:Bind Jquery event to table rows dynamically added to table将 Jquery 事件绑定到动态添加到表中的表行
【发布时间】:2014-05-05 22:47:30
【问题描述】:

我有一个带有按钮的表格,单击该按钮会在表格中添加 5 行单元格。我想将事件绑定到表格第 5 列中的单元格。所有这些单元格都命名为“Count_”,后跟行号。所以,第 0 行的单元格是:

<td name="CountCell_0">
   <input type="text" name="Count_0">
</td>

我正在尝试使用名称 Count_X 更新输入(其中 X 是行号)。 绑定适用于最初存在于页面上的单元格。但是,使用按钮添加的单元格不会触发该事件。

这是一个动态添加的单元格示例:

<td>
  <input type="text" name="Count_348">
</td>

这是我的 Jquery 事件:

            $(document).ready(
            function() {   
                $(document).on('change','[name^="Count_"]',function() {
                    console.log('here'); //not triggering on dynamic cell
                    var cell = $(this).attr('name');
                    var idx = cell.split('_')[1];
                    var amount = $(this).val() * $('[name="AvgCost_' + idx + '"]').html();
                    $('#ExtendedCostCell_' + idx).html(amount.toFixed(2));
                });

           }
        );

【问题讨论】:

    标签: php jquery html dom


    【解决方案1】:

    我认为问题出在 [name^="Count_"]' 你需要一个选择器所以更改为这个输入[name^="Count_"]' 并且不执行匿名函数

            $(document).ready(
            (function() {   
                $(document).on('change','input[name^="Count_"]',function() {
                    console.log('here'); //not triggering on dynamic cell
                    var cell = $(this).attr('name');
                    var idx = cell.split('_')[1];
                    var amount = $(this).val() * $('[name="AvgCost_' + idx + '"]').html();
                    $('#ExtendedCostCell_' + idx).html(amount.toFixed(2));
                });
    
           }());
        );
    

    【讨论】:

    • 其实他不需要标签名。 [name^="Count_"] 本身就是一个选择器。
    • 你绝对正确。也许该功能没有立即执行
    【解决方案2】:

    我将函数移到准备好的文档之外,现在它在动态行上触发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 2014-09-17
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多