问题
i am using the DataTable plugin to display data in my backend page. The plugin works so far very good except in one situation: I have a table showing all products. For each line of the table i have a link for AJAX activation / deactivation of one product. If i am on the first page the activation / deactivation works fine, but when i choose another page using the DataTable Pagination i cannot activate / deactivate the chosen product. It does not display any error in the Firebug, so i am assuming that somehow the link is not correctly displayed.
Here is my HTML code:
<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>
and right after the HTML code, comes the 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>
回答1:
You need to use event delegation by providing selector as a second argument in on() call, see example below:
$('table#products').on('click', 'a.status_product', function() {
// activate / deactivate
});
From jQuery on() method documentation:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
See "Direct and delegated events" in jQuery on() method documentation and jQuery DataTables – Why click event handler does not work for more information.
来源:https://stackoverflow.com/questions/39338903/click-event-doesnt-fire-on-pages-other-than-first