【问题标题】:Initialising jQuery DataTables in Wordpress Breaking HTML Table在 Wordpress 中初始化 jQuery DataTables 破坏 HTML 表
【发布时间】:2019-02-17 10:00:22
【问题描述】:

我一直在使用 Wordpress 中的 DataTables,但遇到了一个奇怪的问题,这似乎是 wordpress 特有的问题。

我可以毫无问题地使用以下方法初始化 jQuery DataTable:

<script>
jQuery(document).ready( function () {
    jQuery('#test_table').DataTable( {
    dom: 'lBfrtip',
} );
} );
</script>

但是当我使用 jQuery 功能时,它会消失,将表格渲染回纯 html:

<script>
jQuery(document).ready(function() {
    // Setup - add a text input to each footer cell
    jQuery('#test_table tfoot th').each( function () {
        var title = jQuery(this).text();
        jQuery(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );

    // DataTable
    var table = jQuery('#test_table').DataTable();

    // Apply the search
    table.columns().every( function () {
        var that = this;

        jQuery( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );
</script>

这没有意义,因为上述两种方法在 jsfiddle 中都可以正常工作。有什么想法吗?

【问题讨论】:

  • 我可以确认您的 Datatables 代码工作正常,因此可能是与 Wordpress 的一些交互。您能否提供更多关于如何在 WP 中包含此代码的信息?
  • 感谢您的评论。请看下面的答案。我让它工作了我不知道为什么新代码会有所作为。我只是移动了 var table = jQuery('#test_table').DataTable();到第 2 行。奇怪。

标签: javascript jquery wordpress datatables


【解决方案1】:

感谢您的有道理的回复,

我正在排队我的 .js 文件,如下所述:https://developer.wordpress.org/themes/basics/including-css-javascript/

经过几个小时的折磨,我设法让它工作:

jQuery(document).ready(function() {
    var table = jQuery('#test_table').DataTable();
    // Setup - add a text input to each footer cell
    jQuery('#test_table tfoot th').each( function () {
        var title = jQuery(this).text();
        jQuery(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    });
    table.columns().every( function () {
        var that = this;
        jQuery( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
    });
    });
}); 

我搬家了

var table = jQuery('#test_table').DataTable();

到第 2 行。

如果其他人遇到这个问题,我的设置是:

WordPress 5.0.3 插件: 强大的表格 3.0.5 强大的表单 Pro 3.0.5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 2011-12-13
    • 2015-11-04
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多