当偶数元素被点击时,将类添加到偶数元素,当点击奇数元素时将类添加到奇数元素 [英] Add class to even elements when even element is clicked and add class to odd elements when odd element is clicked

查看:119
本文介绍了当偶数元素被点击时,将类添加到偶数元素,当点击奇数元素时将类添加到奇数元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着一类添加到偶数元素被点击偶数元素时,并添加类点击一个奇怪的元素时,奇数元素。

Im trying to add a class to the even elements when an even element is clicked and add class to the odd elements when a odd element is clicked.

我有第n个孩子(偶数):使用尝试。第n个孩子(奇数),但我似乎无法figiure如何判断点击的元素是奇数还是偶数

I have tried using :nth-child(even) :nth-child(odd) but i cant seem to figiure out how to tell if the element clicked is even or odd.

考虑这个基本的HTML

COnsider this basic HTML

<ul id="list">
    <li>one</li>
    <li>two</li>
    <li>three</li>
    <li>four</li>
    <li>five</li>
    <li>six</li>
    <li>seven</li>
    <li>eight</li>
</ul>

如果你点击'二',元素二,四,SIZ和八个应该强调。如果单击一个,元素一,三,五和七应突出显示。 (当我高亮显示时,我可能只添加一个类:

If you click on 'two', the element two, four, siz and eight should be highlighted. If you click one, the elements one, three, five and seven should be highlighted. (when i say highlighted, i might just add a class :

.red {
    background:red;
}


推荐答案

此处的示例

$("#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.

这篇关于当偶数元素被点击时,将类添加到偶数元素,当点击奇数元素时将类添加到奇数元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆