【问题标题】:Datatables jQuery event works on second page, not on restDatatables jQuery事件适用于第二页,而不是休息
【发布时间】:2017-05-28 19:45:11
【问题描述】:

我制作了以下 jQuery 事件,当您在 second 页面上进行分页时,它实际上工作

但是它不会在第三页和其余页面触发,也没有 console.log 错误。

问题显然在于对 DataTable initComplete 参数的 DOM 重建,我猜这些参数仅适用于第一个结果数据表,这就是为什么它只在第二个结果页面上调用我的 status_icons() 函数而不是其余的。

我的全局函数在点击事件时触发 DataTable 的分页

function status_icons() {

    $('table tr').each(function() {
        if ($(this).find('td').eq(0).text() == '1') {
            $(this).find('td').eq(0).replaceWith('<i class="fa fa-3 fa-check-circle-o datatable-paid-1" aria-hidden="true"></i>');
            $(this).find('.btn-success').eq(0).prop("disabled", true);
            $(this).find('.btn-success').eq(0).text('Paid'); 
        } else {
            $(this).find('td').eq(0).replaceWith('<i class="fa fa-3 fa-exclamation-circle datatable-paid-0" aria-hidden="true"></i>');
        }
    });
}

这就是我构建我的 DataTable 的方式,为第一个结果页面和其余部分调用上述函数

setTimeout(function() {
    $('#invoices-table').DataTable({
        responsive: true,
        columnDefs: [{ orderable: false, targets: [-1, -2, -3] }],
        "lengthMenu": [
            [100, 5, 25, 50, -1],
            [100, 5, 25, 50, "All"]
        ],
        dom: 'Bfrtip',  

        initComplete: function() {
            status_icons() // it executes my function for the first page of results
            var api = this.api();
            // some irrelevant code that uses api and does not cause my issue
            // ...

            $('.paginate_button').on('click', function() {
                status_icons(); // it executes for the second page but not for the rest
            });

        }
    });
}, 3000);

使用

https://cdn.datatables.net/1.10.10/js/jquery.dataTables.js

【问题讨论】:

  • 试试$(document).find('.paginate_button').on(...

标签: javascript jquery datatable


【解决方案1】:

那些分页按钮被重绘...
所以将它们视为“动态的”。

这里需要event "delegation"

使用$(document).on('click','.paginate_button', function() { 从静态元素开始查找,该元素会将事件委托给其实际匹配的子元素。

CodePen ;)

【讨论】:

  • 我非常同意你的逻辑,但实际上并没有奏效。它一直工作到第二个结果页面,甚至试图将其排除在 DataTable 构造的范围之外:-/。它应该工作..
  • 好的...我重现了问题...等一下。 ;)
  • 你可以把它放在initComplete函数中是你想要的......没有区别。 ;) Bonne journée! ;)
  • document 中将发生的每个click 事件上,如果target(事件真正发生的元素)具有类paginate_button,则该事件将被延迟给它。所以这里的“范围”是document。如果您在同一个document 中有多个数据表,则应该将此“范围”降低到表本身(或者可能是它的包装元素)......它只需要是一个静态父元素。
  • mmm... 在委托的 onclick 中添加一个条件,包装所有功能:if( !$(this).hasClass("disabled") ){...} ----- 所以按钮被禁用,什么都不会发生。我编辑了 CodePen,以防不清楚... ;)
猜你喜欢
  • 2013-10-02
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多