简体   繁体   English

活动课程无法正常工作

[英]Active class not working properly

I have some menu items and in the menu I have a plus(+) sign. 我有一些菜单项,并且在菜单中有加号(+)。 When I click on the plus sign it should add a class and look like cross. 当我单击加号时,它应该添加一个类,看起来像十字。 It is happening but when I click the cross sign it does not removing the sign so that I can get the plus sign again. 它正在发生,但是当我单击十字符号时,它不会删除该符号,因此我可以再次获得加号。

$(document).ready(function(){    
  $('.nav-link').click(function(){
    $('.nav-link').removeClass('addplus');
    $(this).addClass('addplus');
  });

});

Here is the Example . 这是示例

The issue is because you are always removing, then immediately adding the class back on the clicked element. 问题是因为您总是要删除,然后立即将类添加回clicked元素。 To fix this exclude the current element from the removeClass() call using not() , then use toggleClass() to add/remove the class to the required element, like this: 要解决此问题,请使用not()removeClass()调用中排除当前元素,然后使用toggleClass()将类添加/删除到所需元素,如下所示:

$('.nav-link').click(function() {
  $('.nav-link').not(this).removeClass('addplus');
  $(this).toggleClass('addplus');
});

Updated fiddle 更新的小提琴

I've gone a bit around about the houses here, but this works using parent and siblings : 我在这里的房子周围走了一些路,但这可以通过parentsiblings

$('.nav-link').click(function() {
    $(this).parent(".nav-item").siblings().children(".nav-link").removeClass('addplus');
    $(this).toggleClass('addplus');
});

I wouldn't do a blanket removeClass across all matching elements like you've done, I'd pick them out by excluding the currently matched element. 我不会像您一样对所有匹配的元素进行全面的removeClass操作,而是通过排除当前匹配的元素来挑选它们。 Revised fiddle: https://jsfiddle.net/epqxb6L7/5/ 修正的小提琴: https : //jsfiddle.net/epqxb6L7/5/

It's because your code is removing and adding the same class every time click event triggers. 这是因为每次click事件触发时,您的代码都将删除并添加相同的类。 Try something like this 试试这个

$(document).ready(function(){    
   $('.nav-link').click(function(){
   $(this).toggleClass('addplus'); //THIS WILL ADD/REMOVE CLASS ALTERNATIVELY
  });
});

You always add the class addplus in the last line of your click handler. 总是在点击处理程序的最后一行添加addplus类。 Try the following instead: 请尝试以下操作:

$(document).ready(function(){    
  $('.nav-link').click(function(){
    if ($(this).hasClass('addplus')) {
      $(this).removeClass('addplus');
    } else {
      $(this).addClass('addplus');
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM