jQuery 单击 Anchor 标签添加一个类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4647098/
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
adding a class on click of Anchor tag
提问by Vivek
Lets say I have the following HTML...
假设我有以下 HTML ...
<a class="active" href="#section1">Link 1</a>
<a href="#section2">Link 2</a>
When a link 2 is clicked I would like it to receive the active class and remove the class from link 1 itself so it would effectively become:
当单击链接 2 时,我希望它接收活动类并从链接 1 本身中删除该类,这样它就会有效地变为:
<a href="#section1">Link 1</a>
<a class="active" href="#section2">Link 2</a>
This should work both ways. Ie. whatever link is clicked gets the class and removes it from the other.
这应该是双向的。IE。单击任何链接都会获取该类并将其从另一个链接中删除。
How can this be done with jQuery? Thanks in advance!
这如何用 jQuery 完成?提前致谢!
回答by switz
$("a").click(function(){
$("a.active").removeClass("active");
$(this).addClass("active");
});
Edit: added jsfiddle
编辑:添加了jsfiddle
回答by gertas
Just use: addClassand removeClass
只需使用:addClass和removeClass
But first limit your activable links with second class ('activable') to not affect other links on page:
但首先将您的可激活链接限制为第二类(“可激活”),以免影响页面上的其他链接:
$("a.activable").click(function(){
$("a.activable.active").removeClass("active");
$(this).addClass("active");
});
With HTML:
使用 HTML:
<a class="activable active" href="#section1">Link 1</a>
<a class="activable" href="#section2">Link 2</a>
回答by andres descalzo
HTML:
HTML:
<a class="myrefclass" href="#section1">Link 1</a>
<a class="myrefclass active" href="#section2">Link 2</a>
JS:
JS:
var ref = $("a.myrefclass");
$(ref).bind('click', function() {
if (!$(this).hasClass("active")) {
$(ref).removeClass("active");
$(this).addClass("active);
}
});
JS II (for comment):
JS II(评论):
var ref = $("a.myrefclass");
$(ref).bind('click', function(ev) {
if (!$(this).hasClass("active")) {
ev.stopPropagation();
return false;
}
$(ref).removeClass("active");
$(this).addClass("active);
});