单击时添加和删除类 [英] Add and remove class on click

查看:54
本文介绍了单击时添加和删除类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标签菜单,我希望onlick添加一个 class =selected - 并且点击其他标签之一,该课程应该是从当前链接中删除,然后添加到我点击的链接...

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...

我试过这个但是没有工作

I've tried this but didnt work

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

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>

推荐答案

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

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

this is the target of the click event toggleClass method adds a class if it is not present else removes it.

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

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

这篇关于单击时添加和删除类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆