使用 jquery 更改 onClick 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15645626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change class onClick using jquery
提问by Jeremy
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.
我有一个使用 class="active" 显示活动状态的导航。单击链接时,我需要将“活动”类添加到单击的链接,并从所有其他链接中删除“活动”类。
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!
任何帮助将不胜感激!
回答by Marcus
Try this:
尝试这个:
function changeClass() {
$('#referNav a').removeClass('active');
$(this).addClass('active');
}
And you should also bind the function in javacript like so:
您还应该像这样在 javacript 中绑定函数:
$('#referNav a').on('click', changeClass);
That way, as Travis J points out in the comments, $(this)
will reference the correct object.
这样,正如 Travis J 在评论中指出的那样,$(this)
将引用正确的对象。
回答by Travis J
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.
您需要做的是创建一个调用的函数changeClass
,该函数将查找class="active"
然后删除该类。然后将类名分配给active
刚刚单击的元素。将被单击的元素传递给函数将是有益的,这样您就可以知道单击了哪个元素。否则,您可以使用全局对象event
并查看当前targetElement
是什么。
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
我不愿意只展示一个解决方案,因为不鼓励这类问题。人们应该做自己的工作。但是,由于这是一个简单的情况:jsFiddle demo
$("div[id^=referLink] a").click(function(){
$('#referNav .active').removeClass('active');
$(this).addClass('active');
});
回答by Gokul Kav
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');
});