添加类&删除类不起作用
我有一个菜单,它应该作为单击菜单工作,因此当单击按钮时会出现一个菜单,当再次单击按钮时,菜单应该消失,但我无法让它工作?
我有这个脚本,
<script type="text/javascript">
$(document).ready(function() {
$('#dropdown').click(function(){
setTimeout(function(){
$('#dropdown').attr("id", "dropdown2");
$('#dropmenu').addClass("open");
//$('#dropmenu').fadeIn('fast');
},500);
})
$('#dropdown2').click(function(){
setTimeout(function(){
$('#dropdown').attr("id", "dropdown");
$('#dropmenu').removeClass("open");
//$('#dropmenu').fadeIn('fast');
},500);
})
});
</script>
它在添加类时有效,但是当我再次单击按钮时,它不会删除“打开”类
I have a menu, it should work as a click menu, so when clicking the button a menu will appear, and when clicking the button again, the menu should disapear, but i cant get it to work ?
I've got this script
<script type="text/javascript">
$(document).ready(function() {
$('#dropdown').click(function(){
setTimeout(function(){
$('#dropdown').attr("id", "dropdown2");
$('#dropmenu').addClass("open");
//$('#dropmenu').fadeIn('fast');
},500);
})
$('#dropdown2').click(function(){
setTimeout(function(){
$('#dropdown').attr("id", "dropdown");
$('#dropmenu').removeClass("open");
//$('#dropmenu').fadeIn('fast');
},500);
})
});
</script>
It works fint when adding the class, but then when im clicking the button again, it wont remove the class "open"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编写
$('#dropdown').attr("id", "dropdown2");
后,第二个处理程序中的代码没有#dropdown
元素匹配。此外,当您绑定第二个处理程序时,还没有
#dropdown2
元素。 (live
事件可以解决这个问题)相反,您应该使用
切换
事件,它允许您绑定多个click
处理程序,这些处理程序将执行每个其他点击。例如:
After you write
$('#dropdown').attr("id", "dropdown2");
, there is no#dropdown
element for the code in the second handler to match.Also, when you bind the second handler, there is no
#dropdown2
element yet. (live
events would solve that issue)Instead, you should use the
toggle
event, which allows you to bind multipleclick
handlers that will execute every other click.For example:
它不起作用的原因是当您注册点击处理程序时 dropdown2 id 不会退出。你可以使用 live 来克服这个问题,但最好使用类:
The reason it isn't working is that the dropdown2 id doesn't exit when you register the click handler. You could use to live to overcome this, but it is better to use classes:
我更新了上面的代码,对我来说很有用。请尝试这个,
I updated above code, working good for me. Please try this,