Javascript addClass removeClass未按要求工作
Javascript addClass removeClass not working as desired
当我点击图标时,我希望它打开/关闭。
在我的html文件中,我有:
<div class="startSharing"></div>
在我的js:
$('.startSharing').click(function() {
$(this).removeClass('startSharing');
$(this).addClass('stopSharing');
});
$('.stopSharing').click(function() {
$(this).removeClass('stopSharing');
$(this).addClass('startSharing');
});
当它从打开切换到关闭时,它工作得很好,但我不明白为什么它在关闭时仍会进入"startSharing"部分
谢谢你的帮助。
在这种情况下,您将处理程序设置为特定的元素。一旦它们被设置,它们就被设置了,而不考虑选择器的变化。
如果它们都是这样开始的,那么您可以在.startSharing
元素上定义它。然后,您可以使用.toggleClass()
轻松地打开/关闭它们:
$('.startSharing').click(function() {
$(this).toggleClass('startSharing stopSharing');
});
您也可以像这样委托点击事件:
$('body').on('click', '.startSharing', function() {
$(this).removeClass('startSharing').addClass('stopSharing');
});
$('body').on('click', '.stopSharing', function() {
$(this).removeClass('stopSharing').addClass('startSharing');
});
这样做还将允许动态生成触发事件。在您的案例中,.stopSharing
是动态生成的。
使用事件委派
$('#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>
相关文章:
- jQuery addClass/removeClass在调试期间工作,但不能正常执行
- .addClass不工作(刷新时被删除)
- Jquery日期选择器addclass()不工作
- addClass 和 removeClass 无法正常工作
- Javascript addClass removeClass未按要求工作
- addClass()函数没有'ajax调用后无法工作
- 为什么不;我的jquery工作(使用延迟、hasclass、addclass、removeclass、keyUp、key
- HTML菜单上的addClass/removeClass是't工作
- addClass()在jQuery的if子句中未按预期工作
- 为什么我的addClass removeClass和事件处理程序不能按预期工作
- JavaScript的addClass不工作与PHP GET['page']
- jquery中的addClass不像我想的那样工作
- 为什么. addclass()和. removeclass()不能按预期工作?
- addClass脚本不能在导航元素上工作
- 在Backbone应用中使用addClass()和CSS过渡的渲染功能不能正常工作
- 不能得到onclick $(this).addClass来工作
- 我的javascript removeClass + addClass时,点击只在Chrome上工作,而不是Firefo
- jquery addClass和removeClass不像我预期的那样工作
- 来自JSON的jquery.addClass不是相应的工作
- 扩展jQuery addClass来接受回调——它是如何工作的