我正在使用 DataTable 插件在我的后端页面中显示数据。到目前为止,该插件运行得非常好,除了一种情况:我有一张显示所有产品的表格。对于表的每一行,我都有一个用于 AJAX 激活/停用一个产品的链接。如果我在第一页,激活/停用工作正常,但是当我使用数据表分页选择另一个页面时,我无法激活/停用所选产品。它不会在 Firebug 中显示任何错误,因此我假设链接未正确显示。
这是我的 HTML 代码:
<table id="products" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Copy</th>
<th>Status</th>
<th>Delete</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
<th>Copy</th>
<th>Status</th>
<th>Delete</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>1</td>
<td><a href="http://deals/admin/products/edit/1">Iphone</a></td>
<td><a href="http://deals/admin/products/copy/1"><span class="glyphicon glyphicon-floppy-disk"></span></a></td>
<td><a href="#" data-href="1" class="status_product"><span id="span_1" class="glyphicon glyphicon-ok-sign"></span></a></td>
<td><a href="#" data-href="1" class="delete_product"><span class="glyphicon glyphicon-remove"></span></a></td>
</tr>
</tbody>
HTML 代码之后是 Javascript:
<script>
$(document).ready(function() {
$('#products').DataTable();
$('table#products td a.status_product').click(function() {
// activate / deactivate
});
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
</script>
最佳答案
您需要通过在 on() 中提供选择器作为第二个参数来使用事件委托(delegate)。调用,请参见下面的示例:
$('table#products').on('click', 'a.status_product', function() {
// activate / deactivate
});
来自 jQuery on()方法文档:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
请参阅 jQuery 中的“直接事件和委托(delegate)事件”on()方法文档和 jQuery DataTables – Why click event handler does not work了解更多信息。
关于javascript - Click 事件不会在除第一个页面以外的页面上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39338903/