简体   繁体   中英

jQuery Traversing Dynamically generated DOM (next(), prev())

I have an HTML table and jQuery handlers to move rows up and down, using .next() and .prev(), but I also want to add new rows and after adding new row and trying to move old rows up or down they move more positions than expected. Here is an example on jsfiddle http://jsfiddle.net/3CQYN/

$(function() {

    initControls();

    $('.new').click(function() {

        $('<tr><td>TEST</td><td><a href="#" class="up">Up</a> <a href="#" class="down">Down</a></td></tr>').appendTo($('table tbody'));

        initControls();

    });

});

function initControls()
{
    $('.down').click(function() {
        var parentRow = $(this).closest('tr');  

        parentRow.insertAfter(parentRow.next());
});

$('.up').click(function() {
        var parentRow = $(this).closest('tr');  

        parentRow.insertBefore(parentRow.prev());
    });
}

Try to move rows up and down, then add few new rows and move the OLD rows up and down again and you'll see the problem.

Every time you add a new row, you rebind the handlers, ending up with multiple handlers bound to individual up and down links. Instead, use event delegation (only executed once, on DOM ready):

$(document).on('click', '.down', function() {
    // ...
});

$(document).on('click', '.up', function() {
    // ...
});

http://jsfiddle.net/Gt4Zq/

Note that if you can find a container to bind to that is closer to the elements than document , that would be preferable.

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