开发者

Removing a class from UL LI but not UL LI UL LI with jQuery

I'm modifying an accordion script to add the class active to the link that gets clicked, but for sub items, I'm having an issue.

Basically, if you click on a child of the accordion, I need it to also add the class active without removing it from the parent. Like this

parent-item
parent-item (active)
   sub-item
   sub-item (active)
   sub-item
parent-item
parent-item

Here's the bit of script currently:

$("#menu li a").rem开发者_StackOverflowoveClass("active");
$(this).addClass("active");

Thanks, just post a comment if you need clarification.

EDIT:

The children elements aren't technically children of the same thing, so .parent() won't work.

<li>
    <a href="#">parent-item</a>
    <ul>
        <li><a href="#">sub-item</a>
    </ul>
</li>


You can try:

$(this).parent().siblings().children('a').removeClass("active");
$(this).addClass("active");

This will remove the .active on the same level elements


Something like:

$("#menu > ul").removeClass("active");
$(this).parent("li").parent("ul").addClass("active");

Should add an active class to the relevant parent-item.


This example maybe will help you

<ul id='menu'>
<li>
    <a>MElement1</a>
</li>
<li>
     <a>MElement2</a>
 </li>
</ul>
<ul id='menu1'>
<li>
    <a>Element1</a>
</li>
<li>
    <a>Element2</a>
</li>
</ul>

css

.deneme{
    color:red;
}

.deneme1{
color:blue;
}

js

$('#menu').addClass('deneme')
$('#menu1 li a').addClass('deneme1')

$('#menu').live('click',function(){
    $(this).toggleClass('deneme')
})
$('#menu1 li a').live('click',function(){
    $(this).toggleClass('deneme1')
})

and u can check from here http://jsfiddle.net/h7fvW/


You mean something like this?

$("#menu li a").removeClass("active");
$(this).addClass("active");
$(this).parent().addClass("active");

After removing the active class just add it back to the selected item and its parent.

EDIT: Looking at your HTML fragment you should be able to walk back up as far as you need and then come back down. e.g.

$("#menu li a").removeClass("active");
$(this).addClass("active");
$(this).parent().parent().children("a").addClass("active");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜