Jquery甚至奇怪的选择器不适用于动态内容

时间:2015-01-04 22:49:10

标签: jquery

通过移动元素来更改内容后,我想为它们重新应用oddeven样式。但在这个具体的例子中,它不起作用。不幸的是,我无法使用CSS:偶数和:奇数选择器(在IE 8中不支持)。请帮忙。

http://jsfiddle.net/rghg3j5v/

function highlightRows() {
    $('table tr:odd td').addClass('odd');
    $('table tr:even td').addClass('even');
}

highlightRows(); // Initial styling

$('.up').click(function() {
    var parent = $(this).parents('tr');
    var prev = $(parent).prev();

    $(parent).insertBefore(prev);
    highlightRows(); // Re-apply style when element is moved
});

$('.down').click(function() {
    var parent = $(this).parents('tr');
    var next = $(parent).next();

    $(parent).insertAfter(next);
    highlightRows(); // Re-apply style when element is moved
});

1 个答案:

答案 0 :(得分:5)

你必须删除要重置的旧类,否则这些元素最终会同时出现两个类,第一个是预先设定的

function highlightRows() {
    $('table tr td').removeClass('odd even');
    $('table tr:odd td').addClass('odd');
    $('table tr:even td').addClass('even');
}

FIDDLE