jQuery datatables: test if datatables plugin is in

2019-03-24 06:15发布

I want to check if a table element with say, id="datatable" is datatables-initialized. Something like this:

if ($('#datatable').dataTable().initialized) {
  alert("initialized!");
}
else {
      alert("not initialized!");
    }

How can I do that? Thanks!

6条回答
再贱就再见
2楼-- · 2019-03-24 06:28

After you've called .dataTable() does it do anything to the table that makes it identifiable? i.e. does it add a new class "initialised" or something like that? If so, you could just loop through the items like so:

$('.datatable').each(
    function(index, element) {
        var _table = $(element);
        if (_table.hasClass('initialised')) {
            // Do stuff
        } else {
            // Do stuff
        }
    }
);

Apologies if this isn't what you mean. It's not clear in your question what "dataTable()" actually does.

查看更多
女痞
3楼-- · 2019-03-24 06:37

I have used callback() function to do the same in my scenario. Thought of sharing this as an alternate approach

/* During Initialization */
var isTableInitialized = false;
$('#datatable').dataTable({/* your dataTable configurations*/},initializeDT());

/* Implement a callback function to set the value */
function initializeDT() {
    isTableInitialized = true;
}

Later in code..

/* Checking for Initialization is easier*/
if(isTableInitialized) {
    /* Do something here */
} else {
    /* Do something here */
}
查看更多
SAY GOODBYE
4楼-- · 2019-03-24 06:44

First, add a special class name when you're initializing datatables:

$('.datatable').not('.initialized').addClass('initialized').dataTable()

And now you can tell them apart by class name:

alert( $('#datatable').hasClass('initialized') )
查看更多
相关推荐>>
5楼-- · 2019-03-24 06:47

I feel following is the right answer to this.

$(document).ready(function(){
    if (jQuery().dataTable) {
         // your code to do some detaul set ups 
    }
});

For example

$(document).ready(function(){
    if (jQuery().dataTable) {

            $.extend( $.fn.dataTable.defaults, {
                iDisplayLength : 200,
                aLengthMenu : [[100, 200, 300, -1], [100, 200, 300, "All"]],
            });
        }
});

By this way you if(jQuery().<libname>) should be able to check any library loaded or not.

查看更多
Evening l夕情丶
6楼-- · 2019-03-24 06:49

You can the fnIsDataTable function in jQuery datatable

var ex = document.getElementById('example');
if ( ! $.fn.DataTable.fnIsDataTable( ex ) ) {
  $(ex).dataTable();
}

You can find more information in api

查看更多
beautiful°
7楼-- · 2019-03-24 06:49

Datatable has a method to check if an element has been initialized as a datatable or not - $.fn.DataTable.fnIsDataTable

tableElement = document.getElementById('your table ID');
$.fn.DataTable.fnIsDataTable(tableElement); // returns true or false
查看更多
登录 后发表回答