简体   繁体   中英

jQuery button doesn't work after sorting datatable

I have a jQuery function which looks like this:

function unlock_reservation_columns(resid) {

    $('.unlock-columns').click( function(event) {

        event.preventDefault();
        $(this).closest('tr').find('.columns-locked').removeClass('columns-locked');
        $(this).html('<i class="fa fa-lock"></i> Lock Columns');
        $(this).attr('class', 'lock-columns');

        new PNotify({
            title: 'We have unlocked this reservation..',
            text: 'Reservation Unlocked',
            type: 'success'
        });
        var url = $(this).attr("href");
        var url_id = url.replace(/[^0-9]/g, '')
        $.get(url, function (data) {

            var confirm_changes = confirm('Do you wish to edit unlocked information?');

            if (confirm_changes) {
                window.location.href = '/reservations/database/edit/' + url_id;
            }
            else {
                location.reload()
                return false;
            }
        });
    });
});

<a class="unlock-columns" href="<?php echo $row->unlock_url; ?>"><i class="fa fa-unlock"></i> Unlock Columns</a>

The button "unlock-columns" is located inside a Datatable custom column. Now when the page is only initialized this button works fine. After i sort something in the table. the (data-order-by) and click the button it doesn't work.. like after sorting it stops working. any ideas why?

Use a delegated event handler

$('#tableId').on('click', '.unlock-columns', function(event) {

instead. As it is now you only attach the click handler to visible rows upon initialisation, not rows injected later on (as when you are paginating, sorting etc).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM