jquery - 触发事件时,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吗?
解决方案
请记住,在您绑定事件时,可能当时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
});
推荐阅读
- lua - 如何在 powerdns 中为 aaaa 请求替换 ipv4 答案?
- android - Android 导航组件中的目的地链接
- p2p - 一个bit torrent客户端如何知道上传和下载的数据量等传输细节?
- postgresql - 我应该如何设计用户屏蔽系统?
- java - 参考列不会保存在单向一对多关系休眠中
- javascript - 覆盖对象内调用其初始实现的函数
- c++ - 用于枚举绑定但未连接的套接字的 WIndows API
- python - 寻找彼此靠近的对象边界
- php - 如何在php中创建文件扫描器时修复超时
- unity3d - Unity 材质中的发射对附近的静态物体没有影响