javascript - Click 事件不会在除第一个页面以外的页面上触发

标签 javascript jquery pagination datatables

我正在使用 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/

相关文章:

javascript - 修复用于实时图表的 google charts api 的 JSON 数据格式

javascript - Math.min throw Nan 数学

javascript - 服务器上存储的示例歌曲

javascript - 如何使用javascript限制文本框中的中文字符

javascript - 使用 Javascript 将文本居中并使用 css3 viewport 调整大小在调整大小时会很不稳定

php - 如何在执行结束前逐步打印SQL查询结果?

javascript - jqtree无法使用loadDataFromUrl函数加载数据

javascript - 设置 colorbox lightbox ajax href 变量

php - 非上一个时显示下一个帖子

php - 简单的 PHP MySQL 分页(显示更多按钮,带参数)