jQuery 在标签内的跨度上添加/删除类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1952172/
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
add / remove class on span inside a tag
提问by lnvrt
I've tried various options but can't get the silly thing to work. How do I get the span inside an < a > tag within an < li > to change class to "active"; then remove it when another < a > is clicked?
我尝试了各种选择,但无法让愚蠢的事情发挥作用。如何在 < li > 中的 < a > 标记内获取跨度以将类更改为“活动”;然后在单击另一个 < a > 时将其删除?
<ul id="dumb">
<li><a href="#">Something<span></span></a></li>
<li><a href="#">Something Else<span></span></a></li>
</ul>
Clicking the < a > should give the span a class of "active" and when another is clicked, it should remove it from the original and add it to the span of that < a >...
单击 < a > 应该给跨度一个“活动”类,当另一个被单击时,它应该将其从原始文件中删除并将其添加到该 < a >...的跨度中。
Thanks!
谢谢!
回答by rahul
$(function(){
$("#dumb > li > a").click ( function(){
$("#dumb > li > a > span").removeClass ( 'active' );
$(this).find('span').addClass('active');
return false;
});
});
回答by James Wiseman
Try this:
尝试这个:
$(document).ready(function(){
var $MySpans = $("#dumb li a span");
$MySpans.click(function(){
$MySpans.removeClass();
$(this).addClass("active");
});
});
You might try this as well as it will be a faster selector if it works:
你也可以试试这个,因为如果它有效,它会是一个更快的选择器:
var $MySpans = $("#dumb>li>a>span");
回答by Milap Jethwa
jQuery('#dumb li a span').addClass( "active" );
jQuery('#dumb li a span').addClass("active");