首页 > 解决方案 > 触发事件时,ajax调用后创建的按钮不起作用

问题描述

我在html中有以下代码:

<table class="table table-striped">
<thead class="inner">
    <tr>
        <th>Name</th>
        <th>Parent</th>
        <th>Priority</th>
        <th>Action</th>
    </tr>
</thead>
<tbody id="check">
    <tr>
        <td><a href="">test</a></td>
        <td>null</td>
        <td>0</td>
        <td>
            <button value="3" type="button" class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
        </td>
    </tr>
    <tr>
        <td><a href="">Lifestyle</a></td>
        <td>null</td>
        <td>1</td>
        <td>
            <button value="2" type="button" class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
        </td>
    </tr>
    <tr>
        <td><a href="">Travel</a></td>
        <td>null</td>
        <td>1</td>
        <td>
            <button value="1" type="button" class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
        </td>
    </tr>
</tbody>

我在页脚中有以下代码:

$("#check tr td button").click(function () {
    alert('here');
});

但该事件似乎不起作用。为什么我的代码不起作用?表中的数据是在 ajax 调用之后创建的。是因为ajax吗?

标签: jqueryhtml

解决方案


请记住,在您绑定事件时,可能当时DOM 中不存在对象$("#check tr td button") !

因此,解决方案是 ajax 完成后的绑定事件。

将您的代码放入ajax的成功方法中

$.ajax({
 url: 'url',
 data: [],
 success: function() {
   // render table code
   // bind event here
   $("#check tr td button").click(function () {
    alert('here');
   });
 }
});

或者您可以使用文档的事件单击。

  $(document).on("click", "#check tr td button", function() {
    // do something you want here 
  });

推荐阅读