【问题标题】:Adding a new row which contains button into table using jQuery [duplicate]使用jQuery将包含按钮的新行添加到表中[重复]
【发布时间】:2016-12-16 21:25:21
【问题描述】:

我正在使用以下代码在名为people_table 的表中添加一个新行:

  $("#add_new_row").click(function() {
    console.log("***");
    $('table#people_table').append('<tr><td>Dima</td><td>Petrov</td><td>30</td><td><button type="button" class="btn btn-success" id="change_4">Change</button></td></tr>');

  });
...
<button type="button" class="btn btn-primary" id="add_new_row">Add new row</button>
<table class="table table-hover" id="people_table">
   <tr>
    <th>Name</th>
    <th>Surname</th>
    <th>Age</th>
    <th>Modify</th>
   </tr>
   {% for person in people %}
   <tr>
     <td>{{ person[1] }}</td>
     <td>{{ person[2] }}</td>
     <td>{{ person[3] }}</td>
     <td><button type="button" class="btn btn-success" id="change_{{ person[0] }}">Change</button></td>
   </tr>
   {% endfor%}
</table>

但是在添加行之后是下面的函数

  $("button[id^='change_']").click(function() {
    console.log("+++");
  });

对新添加的行中的按钮不起作用,但对其他按钮有效。有什么问题?

【问题讨论】:

  • 它不起作用,因为代码在您将按钮添加到页面之前运行。您要么需要直接绑定事件,要么使用事件委托。
  • 您应该使用 .on() 函数而不是 .click() 因为 .click() 不适用于动态元素。

标签: javascript jquery twitter-bootstrap frontend


【解决方案1】:

试试这个enter link description here

 $("#add_new_row").click(function() {
    console.log("***");
    $('table#people_table').append('<tr><td>Dima</td><td>Petrov</td><td>30</td><td><button type="button" class="btn btn-success" id="change_4">Change</button></td></tr>');
addNewRow();
  });

  function addNewRow()
  {
   $("button[id^='change_']").click(function() {
    alert('click')
  });
  }

【讨论】:

    【解决方案2】:

    对于新添加的 dom 元素 .click() 在这种情况下将没有用,您必须使用 .on('click' 事件列表器。

    $("button[id^='change_']").on('click',function() {
        console.log("+++");
    });
    

    【讨论】:

      【解决方案3】:

      试试这个,对动态添加的元素使用方法...

       $(document).on('click', 'button[id^="change_"]', function() {
              console.log("+++");
            });
      

      【讨论】:

        猜你喜欢
        • 2012-11-19
        • 2018-08-29
        • 2015-08-25
        • 1970-01-01
        • 1970-01-01
        • 2018-12-19
        • 2021-06-18
        • 2014-06-17
        • 1970-01-01
        相关资源
        最近更新 更多