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 badges3 Answers
Reset to default 5Try 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
版权声明:本文标题:javascript - Change class onClick using jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741639483a2389831.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论