0

我有一个 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());
    });
}

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

4

1 回答 1

1

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

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

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

http://jsfiddle.net/Gt4Zq/

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

于 2013-09-10T21:50:05.953 回答