admin管理员组

文章数量:1296401

I have a navigation that shows an active state using class="active". When a link is clicked, I need to add the "active" class to to the clicked link, and remove the "active" class from all other links.

Here's my code:

<div id="referNav">
<div id="referLink1"><a href="javascript:;" onClick="changeClass();" class="active"></a></div>
<div id="referLink2"><a href="javascript:;" onClick="changeClass();" class=""></a></div>
<div id="referLink3"><a href="javascript:;" onClick="changeClass();" class=""></a></div>
</div>

Any help would be greatly appreciated!

I have a navigation that shows an active state using class="active". When a link is clicked, I need to add the "active" class to to the clicked link, and remove the "active" class from all other links.

Here's my code:

<div id="referNav">
<div id="referLink1"><a href="javascript:;" onClick="changeClass();" class="active"></a></div>
<div id="referLink2"><a href="javascript:;" onClick="changeClass();" class=""></a></div>
<div id="referLink3"><a href="javascript:;" onClick="changeClass();" class=""></a></div>
</div>

Any help would be greatly appreciated!

Share Improve this question asked Mar 26, 2013 at 19:20 JeremyJeremy 1,1615 gold badges20 silver badges31 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Try this:

function changeClass() {
    $('#referNav a').removeClass('active');
    $(this).addClass('active');
}

And you should also bind the function in javacript like so:

$('#referNav a').on('click', changeClass);

That way, as Travis J points out in the ments, $(this) will reference the correct object.

jsFiddle

What you are going to need to do is make a function called changeClass which will look for class="active" and then remove that class. Then assign the class name active to the element which was just clicked. It would be beneficial to pass the element being clicked to the function so you will know which element were clicked. Otherwise you can use the global object event and see what the current targetElement was.

I am reluctant to just show a solution because this type of question is not encouraged. People should do their own work. However, since this is a simple situation: jsFiddle demo

$("div[id^=referLink] a").click(function(){
 $('#referNav .active').removeClass('active');
 $(this).addClass('active');
});

My solution

 $('#referNav').on('div','click',functin(e){
    $(e.target).closest('div[class^="referLink"]').siblings().find('a').removeClass('active');
    $(e.target).closest('div').find('a').addClass('active');
    });

本文标签: javascriptChange class onClick using jqueryStack Overflow