Jquery 事件触发时,ajax调用后创建的按钮不起作用
我有以下html代码:Jquery 事件触发时,ajax调用后创建的按钮不起作用,jquery,html,Jquery,Html,我有以下html代码: <table class="table table-striped"> <thead class="inner"> <tr> <th>Name</th> <th>Parent</th> <th>Priority</th> <th>Action</th> </
<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>
但这项活动似乎并不奏效。为什么我的代码不起作用?表中的数据是在ajax调用之后创建的。是因为ajax吗 事件在元素存在于
DOM
之前注册,这就是函数未被触发的原因。解决方案是在ajax
之后定义代码,或者使用事件委托,如下所示
$(document).ready(function() {
$(document).on("click", "#check tr td button", function() {
alert('here');
});
});
事件在元素存在于
DOM
之前注册,这就是函数未被触发的原因。解决方案是在ajax
之后定义代码,或者使用事件委托,如下所示
$(document).ready(function() {
$(document).on("click", "#check tr td button", function() {
alert('here');
});
});
请记住,在绑定事件时,可能当时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
});
请记住,在绑定事件时,可能当时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
});
试试这个:
$(document).on("click", "#check tr td button", function() {
alert('here');
});
或
$(document).ready(function() {
$(document).on("click", "#check tr td button", function() {
alert('here');
});
});
试试这个:
$(document).on("click", "#check tr td button", function() {
alert('here');
});
或
$(document).ready(function() {
$(document).on("click", "#check tr td button", function() {
alert('here');
});
});