给出一个“selected”类.点击另一个<a>然后删除类,如果它是相同的<a>

Give a class of "selected" when clicked on another <a> then remove the class if it's the same <a>

本文关键字:删除 然后 如果 另一个 一个 selected      更新时间:2023-09-26

我正在尝试改变

$('h2 a').on('click', function(){
    $('h2 a.selected').removeClass('selected');
    $(this).addClass('selected');
});

我创建了一个Accordion,第一个选项卡的类是selected。所以当我点击另一个选项卡时,它从第一个选项卡中删除了selected类,并给出了我点击的selected,如果我点击我刚刚打开的同一个选项卡,它删除了selected

您可以使用.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>

请检查下面的答案,在h2标签中添加一个类,因此它不适用于其他h2标签。当你点击任何,只要删除"选定"类,并添加"选定"类在当前元素。

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>
相关文章: