Toggle not working with DataTable responsive

2019-08-27 16:30发布

问题:

This is how I am coding:

$(document).ready(function () {

    $("[id^=btnToggle]").click(function () {
        $('#infoToggle' + this.id.match(/\d+$/)[0]).toggle();
    });

    $('#dataTables-example').DataTable({
        responsive: true
    });

});

Here this code $("[id^=btnToggle]") is not working, but when I remove $('#dataTables-example') it is working fine.

I tried reversing their positions, I tried using separate document ready function, it did not work.

Please let me know how to fix this?

Thanks

回答1:

The dom(#dataTables-example) is modified when after calling the datatable event. due to which inner elements no more have previously attached events .You need to use event delegation in this case:

 $("body").on('click','[id^=btnToggle]',function () {
    $('#infoToggle' + this.id.match(/\d+$/)[0]).toggle();
});