在单击的 li 上添加类并从兄弟姐妹中删除类 [英] Addclass on clicked li and remove class from siblings

查看:28
本文介绍了在单击的 li 上添加类并从兄弟姐妹中删除类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击时,我想将一个类添加到锚标记,并从所有同级中删除该类.但是,我当前的代码似乎没有从其他元素中删除该类,即使它似乎在单击时添加了该类.

On click I want to add a class to an anchor tag, and remove that class from all of the siblings. However, my current code doesn't seem to remove the class from the other elements even though it does seem to add the class on click.

这是我的代码:

$("ul li").each(function(){
    $(this).click(function(){
       $(this).children().addClass('cell-selected').siblings().removeClass('cell-selected');
    });
});

.cell-selected { color: #fff; background: #5b2200; border-color: #ce5209; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li><a class="cell">Plan 1.1</a></li>
    <li><a class="cell">Plan 1.2</a></li>
    <li><a class="cell">Plan 1.3</a></li>
</ul>
<ul>
    <li><a class="cell">Plan 2.1</a></li>
    <li><a class="cell">Plan 2.2</a></li>
    <li><a class="cell">Plan 2.3</a></li>
</ul>

上传于 http://jsfiddle.net/9wky66ju/24/

推荐答案

jsFiddle Demo

您可以使用 .parent() 返回到兄弟姐妹,但是您需要选择类 cell-selected 以便从那些元素.

You can use .parent() to get back to the siblings, but then you will need to select the class cell-selected in order to remove that class from those elements.

$("ul li").click(function(){ // don't need each (click does this internally)
 $(this).children().addClass('cell-selected') //add cell-selected class to a
 .parent() //go back to li
 .siblings() //look at siblings
 .find('.cell-selected') //find cell-selected elements
 .removeClass('cell-selected'); //remove the class
});

这篇关于在单击的 li 上添加类并从兄弟姐妹中删除类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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