I am trying to change
$('h2 a').on('click', function(){
$('h2 a.selected').removeClass('selected');
$(this).addClass('selected');
});
I made an Accordion, the first tab has class selected
. So when I click on another tab, it removes selected
class from the first tab and gives the one I clicked on selected
, if I click on the same tab I just opened, it removes selected
.
答案 0 :(得分:1)
您可以使用.is()
,.filter()
var h2 = $("h2 a");
h2.on("click", function() {
if ($(this).is(".selected")) {
$(this).removeClass("selected");
} else {
h2.removeClass("selected")
.filter(this).addClass("selected")
}
});
.selected {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<h2>
<a>a</a>
<a>b</a>
<a>c</a>
</h2>
答案 1 :(得分:0)
请您检查下面的答案,在h2标签中添加一个类,这样就不适用于其他h2标签。当您点击任何内容时,只需删除&#34; 选中&#34;上课并添加&#34; 选中&#34;当前元素中的类。
HTML:
<h2 class="headerTitle">
<a href="javascript:void(0)">Headeing1</a>
<a href="javascript:void(0)">Headeing2</a>
<a href="javascript:void(0)">Headeing3</a>
</h2>
Jquery的:
<script type="text/javascript">
jQuery('.headerTitle a').on('click', function(){
jQuery('.headerTitle a').removeClass('selected');
jQuery(this).addClass('selected');
});
</script>
CSS:
<style type="text/css">
.selected{ color: red; }
</style>