Javascript 单击添加和删除类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7077673/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:44:48  来源:igfitidea点击:

Add and remove class on click

javascriptjquery

提问by Benni Russell

I have a tab menu, and i want onlick be be added a class="selected"- and on click on one of the other tabs, the class should be removed from the current link, and then be added to the link i've clicked on...

我有一个选项卡菜单,我希望将 onlick 添加一个class="selected"- 单击其他选项卡之一,应从当前链接中删除该类,然后将其添加到我单击的链接中...

I've tried this but didnt work

我试过这个但没有用

$('.tab-links a').click(function(){
   $(this).toggleClass('selected');
});

And the HTML:

和 HTML:

<section class="tabs">
<nav class="tab-links">
  <ul>
    <li>
      <a href="/min+side/Mine+favoritter" class="ajax-tab-fav myoptionstab">MIne favoritter</a>
    </li>
    <li>
      <a href="/min+side/Mine+jobagenter" class="ajax-tab-jobagents myoptionstab">Jobagenter</a>
    </li>
    <li class="last">
      <a href="/min+side/Rediger+bruger" class="ajax-tab-edituser myoptionstab">Indstillinger</a>
    </li>
  </ul>
</nav>
<div class="clear">
  <!---->
</div>

回答by sv_in

var $links = $('.tab-links a');
$links.click(function(){
   $links.removeClass('selected');
   $(this).addClass('selected');
});

thisis the target of the click event toggleClassmethod adds a class if it is not present else removes it.

this是单击事件toggleClass方法的目标, 如果它不存在,则添加一个类,否则将其删除。

Therefore when you say $(this).toggleClass('selected');, The class is added or removed onlyon the element that was clicked which is clearly not what you want.

因此,当您说$(this).toggleClass('selected');,在单击的元素上添加或删除类时,这显然不是您想要的。

回答by Benni Russell

Using pure javascript:

使用纯 javascript:

function toggleItem(elem) {
  for (var i = 0; i < elem.length; i++) {
    elem[i].addEventListener("click", function(e) {
      var current = this;
      for (var i = 0; i < elem.length; i++) {
        if (current != elem[i]) {
          elem[i].classList.remove('active');
        } else if (current.classList.contains('active') === true) {
          current.classList.remove('active');
        } else {
          current.classList.add('active')
        }
      }
      e.preventDefault();
    });
  };
}
toggleItem(document.querySelectorAll('.link'));

codepen http://codepen.io/8eni/pen/MaGVrq

代码笔http://codepen.io/8eni/pen/MaGVrq

  • Add 'active' class onClick, whilst removing 'active' class from other buttons
  • Toggle class onclick
  • 在点击时添加“活动”类,同时从其他按钮中删除“活动”类
  • 切换类 onclick

回答by solanki...

The given below is awesome and simplest way for addClass and RemoveClass onClick using pure Javascript.

下面给出的是使用纯 Javascript 的 addClass 和 RemoveClass onClick 的很棒和最简单的方法。

Step: 1- write the following code in .html file

步骤:1- 在 .html 文件中写入以下代码

//... code here
<h1 id="kiran" onclick="myFunction(e)">A</h1>
<h1 id="kiran" onclick="myFunction(e)">B</h1>
<h1 id="kiran" onclick="myFunction(e)">C</h1>
<h1 id="kiran" onclick="myFunction(e)">D</h1>
//... code here

Step: 2- Write the following in .js file

步骤:2- 在 .js 文件中写入以下内容

function handleClick(e) {
        var curr = e.target.textContent;
        var elem = document.querySelectorAll('#kiran');
        for (var i = 0; i < elem.length; i++) {
            if (elem[i].textContent === curr) {
                elem[i].className = 'active';
            } else {
                elem[i].className = '';
            }
        }
    };

Step: 3- Write the following in .css file

步骤:3- 在 .css 文件中写入以下内容

.active {
  color: red;
}

回答by SLB

$('.tab-links a').click(function(){
    $('.tab-links a').removeClass('selected')
    $(this).addClass('selected');
});