[英]my javascript prevent my code from working
I have made a side nav bar on toggled and by clicking on any point away from the navbar buttons navbar collapse and buttons not working on clicking on it 我在侧面导航栏上进行了切换,并单击了远离导航栏按钮的任何点,导航栏折叠并且按钮在单击时不起作用
$("#menu-toggle").click(function (e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
$(document).click(function (e) {
if ($('#wrapper').hasClass('toggled')) {
$("#body").click(function (e) {
e.preventDefault();
$("#wrapper").removeClass("toggled");
});
}
});
Don't bind a click event after a click event. 单击事件后不要绑定单击事件。
I don't see the use of the $(document).click(function(e){ })
我看不到
$(document).click(function(e){ })
$("#menu-toggle").click(function (e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
$("#body").click(function (e) {
e.preventDefault();
if ($('#wrapper').hasClass('toggled'))
$("#wrapper").removeClass("toggled");
});
And maybe remove the #
on the $('#body')
if it needs to be on the <body>
tag and the <body>
tag has no id. 也许删除
#
在$('#body')
如果它需要在<body>
标记和<body>
标签没有ID。 Because the #
is an id selector. 因为
#
是ID选择器。
Actually you are overriding the click
event handler on your $("#menu-toggle")
element, you defined in: 实际上,您是在
$("#menu-toggle")
元素上覆盖click
事件处理程序,该元素是在以下位置定义的:
$("#menu-toggle").click(function (e) {
By attaching a click
event to the document
in line: 通过将
click
事件附加到行中的document
:
$(document).click(function (e) {
Because document
is the global element in the page and all other elements are inside of it, so by attaching a click
event handler to the document
you are omitting all other click
handlers on the page. 由于
document
是页面中的全局元素,而所有其他元素都在其中,因此,通过将click
事件处理程序附加到document
您将忽略页面上的所有其他click
处理程序。
Edit: 编辑:
Another issue in your code is that you are attaching a click
event handler inside another click
event handler: 代码中的另一个问题是,您要将
click
事件处理程序附加到另一个click
事件处理程序中:
$(document).click(function (e) {
if ($('#wrapper').hasClass('toggled')) {
$("#body").click(function (e) {
e.preventDefault();
$("#wrapper").removeClass("toggled");
});
}
});
This will attach the second handler, to the body
element, each time the document
is clicked, which is a very wrong approach because you are always attaching a new click
event handler on click of document
which will lead to bad performance in your appplication. 每次单击
document
时,都会将第二个处理程序附加到body
元素上,这是一种非常错误的方法,因为您始终在document
click
上附加新的click
事件处理程序,这将导致应用程序性能下降。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.