質問

I am using DataTables plugin with hidden rows, when using pagination, my click event fails without console error.

This is the function:

$(document).ready(function() {

$('#datatable tbody td a').on('click', function (e) {
    e.preventDefault();
    var nTr = $(this).parents('tr')[0];
    if ( oTable.fnIsOpen(nTr) ) {
        /* This row is already open - close it */
        $(this).addClass('glyphicon-arrow-down');
        $(this).removeClass('glyphicon-arrow-up');
        oTable.fnClose( nTr );
    } else {
        /* Open this row */
        $(this).addClass('glyphicon-arrow-up');
        $(this).removeClass('glyphicon-arrow-down');
        oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
    }
});

});

As you can see i am using delegation, but the function is wrapped in a ready function. I'm certain this is the problem. How do i fix this?

The above question was asked in error, please see my comment under the answer.

役に立ちましたか?

解決

Read .on()

As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.

$('#datatable').on('click', 'tbody td a', function (e) {});

Syntax

$( elements ).on( events, selector, data, handler );

Below code is not Event Delegation

$('#datatable tbody td a').on('click', function (e) {
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top