且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当偶数元素被点击时,将类添加到偶数元素,当点击奇数元素时将类添加到奇数元素

更新时间:2023-12-03 08:09:40

此处的示例

$("#list > li").on("click",function(){
    $('.red').removeClass('red');
    if($(this).index() % 2 == 0) {
       $('#list > li:even').addClass('red');
    } else {
       $('#list > li:odd').addClass('red');
    }
});

使用 $(this).index 0 来确定被点击的元素是偶数还是奇数,然后分别使用 :even / :odd

Use $(this).index() % 2 == 0 to figure out whether the element clicked is even or odd. Then just add the class respectively using :even/:odd.