简体   繁体   English

使用jQuery .removeClass时无反应

[英]Nothing happening when using jQuery .removeClass

The .addClass works properly, however when I attempted to remove the same class on the same element when clicking the .close element, nothing happens. .addClass可以正常工作,但是当我单击.close元素时尝试删除同一元素上的同一类时,什么也没有发生。 I've save the original element in $currGallery . 我已经将原始元素保存在$currGallery When I console.log this on click, it shows the proper element object. 当我单击console.log时,它显示了正确的元素对象。 Would appreciate any help! 将不胜感激!

    var $currGallery = null;

    var handler = function() {
      $currGallery = $(this);
      $(this).addClass("open-gallery");
      //$('.services > li').unbind( "click", handler );
    };

    $('.services > li').bind("click", handler);

    $('.close').click(function(){
      //console.log($currGallery);
      $currGallery.removeClass("open-gallery");
      //$('.services > li').bind( "click", handler );
    });

Most likely ( without seeing your html ) the .close element, is inside the .sevices > li element as well. .close元素很可能( 没有看到您的html )也位于.sevices > li元素内。 So when you click on the .close it correctly removes the class but the event also bubbles up to the .sevices > li which in turn re-adds the class. 因此,当您单击.close它会正确删除该类,但事件也会冒泡到.sevices > li ,这又会重新添加该类。

If that is the case then on the .close handler you need to stop the propagation so that it never reaches the li . 如果是这种情况,则需要在.close处理程序上停止传播,以使它永远不会到达li

$('.close').click(function(e){
  e.stopPropagation();

  $currGallery.removeClass("open-gallery");
});

based on my understanding of the issue you posted, I will suggest you use jquery toggleClass function. 根据对发布问题的理解,建议您使用jquery toggleClass函数。

below is a sample code, and a link to the documentation. 下面是一个示例代码,以及指向文档的链接。

http://api.jquery.com/toggleclass http://api.jquery.com/toggleclass

 <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>toggleClass demo</title> <style> p { margin: 4px; font-size: 16px; font-weight: bolder; cursor: pointer; } .blue { color: blue; } .highlight { background: yellow; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p class="blue">Click to toggle</p> <script> $( "p" ).click(function() { $( this ).toggleClass( "highlight" ); }); </script> </body> </html> 

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

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