简体   繁体   English

Javascript addClass removeClass无法按需工作

[英]Javascript addClass removeClass not working as desired

When I click on the icon, I want it to be switched on/off. 当我单击图标时,我希望将其打开/关闭。

In my html file I have: 在我的html文件中,我有:

<div class="startSharing"></div>

And in my js: 在我的js中:

$('.startSharing').click(function() {
    $(this).removeClass('startSharing');
    $(this).addClass('stopSharing');
});

$('.stopSharing').click(function() {
    $(this).removeClass('stopSharing');
    $(this).addClass('startSharing');
});

It works fine when switching from on to off - but I don't understand why it still goes into "startSharing" section when it is turned off. 从打开切换到关闭时,它可以正常工作-但我不明白为什么关闭时它仍会进入“ startSharing”部分。

Thank you for help. 谢谢你的帮助。

In this case, you're setting the handlers to the particular elements. 在这种情况下,您要将处理程序设置为特定的元素。 Once they're set - they're set, regardless of the selector changing. 设置好之后,无论选择器如何更改,它们都会被设置。

You could just define it on the .startSharing element, if they all start like that. 如果它们都是以.startSharing元素开头的,则可以定义它。 Then, you could use .toggleClass() to easily switch them on/off: 然后,您可以使用.toggleClass()轻松打开/关闭它们:

$('.startSharing').click(function() {
    $(this).toggleClass('startSharing stopSharing');
});

You may also delegate the click event like this: 您也可以像这样委派click事件:

$('body').on('click', '.startSharing', function() {
  $(this).removeClass('startSharing').addClass('stopSharing');
});

$('body').on('click', '.stopSharing', function() {
  $(this).removeClass('stopSharing').addClass('startSharing');
});

Doing it this way will also allow dynamically-generated to trigger events. 以这种方式执行此操作还将允许动态生成触发事件。 In your case, .stopSharing was generated dynamically. 在您的情况下, .stopSharing是动态生成的。

use event delegation 使用事件委托

 $('#container').on('click',".startSharing,.stopSharing",function(){ $(this).toggleClass('startSharing').toggleClass('stopSharing'); }); 
 #container div { width: 250px; height: 100px; } .startSharing { background-color: green; } .startSharing::after { content: "start sharing"; } .stopSharing { background-color: red; } .stopSharing::after { content: "stop sharing"; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div class="startSharing"></div> </div> 

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

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