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

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

本文关键字:next prev DOM Traversing Dynamically generated jQuery      更新时间:2023-09-26

我有一个HTML表和jQuery处理程序,使用.next()和.prev()上下移动行,但我也想添加新行,在添加新行并尝试上下移动旧行后,它们移动的位置比预期的要多。下面是一个关于 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());
    });
}

尝试上下移动行,然后添加一些新行并再次上下移动旧行,您将看到问题。

每次添加新行时,都会重新绑定处理程序,最终将多个处理程序绑定到单独的向上和向下链接。相反,使用事件委托(仅在 DOM 就绪时执行一次):

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

http://jsfiddle.net/Gt4Zq/

请注意,如果你能找到一个比document更接近元素的容器来绑定,那将是可取的。