将事件添加到除使用 jQuery 给定的元素之外的所有元素
我创建了一个日期选择器,它使用 ajax 来填充 ID 为 calendarContainer 的元素。当用户单击按钮调出日历时,我希望用户能够单击屏幕上除日历之外的任何其他位置并将其隐藏。 calendarContainer 位于 dom 的根部,我已经尝试了所有我能想到的方法来使其正常工作。
我已经让日历在未单击时消失。但是,当我单击日历时,它也会消失。我只希望日历在未单击时消失。
这是我尝试过的所有事情。
$(":not(#calendarContainer > table)").live('click', function() { $.Calendar.hide(); });
$(":not(#calendarContainer").live('click', function() { $.Calendar.hide(); });
$(":not(#calendarContainer)").click(function() { $.Calendar.hide(); });
$("body:not(#calendarContainer)").click(function() { $.Calendar.hide(); });
$(":not(#calendarContainer, #calendarData)").live('click', function() { $.Calendar.hide(); });
感谢您的帮助,大都会
I created a date picker that uses ajax to populate an element with an id of calendarContainer. When the user clicks on a button to bring the calendar up, I want the user to be able to click anywhere else on the screen besides the calendar and have it hide. The calendarContainer is at the root of the dom and I have tried everything I can think of to get this working.
I have gotten the calendar to go away when it is not clicked on. However, when I click on the calendar it is also going away. I only want the calendar to go away when it is not clicked on.
Here are all of the things I have tried.
$(":not(#calendarContainer > table)").live('click', function() { $.Calendar.hide(); });
$(":not(#calendarContainer").live('click', function() { $.Calendar.hide(); });
$(":not(#calendarContainer)").click(function() { $.Calendar.hide(); });
$("body:not(#calendarContainer)").click(function() { $.Calendar.hide(); });
$(":not(#calendarContainer, #calendarData)").live('click', function() { $.Calendar.hide(); });
Thanks for any help, Metropolis
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您看到此行为是因为事件冒泡,当您单击日历时,您仍然会点击它的每个父元素,因为它会冒泡。要阻止这种情况,你需要阻止气泡,如下所示:
You're seeing this behavior because events bubble, when you click on the calendar, you're still firing a click on each of it's parent elements because it bubbles up. To stop this, you need to stop the bubble, like this:
你需要选择一些东西。 有效吗
?
You need to select something. Does
work?
您应该查看一下外部插件。基本上它的作用是在 body 元素上设置一个单击事件,然后比较事件目标以查看它是否等于您需要的选择器并从那里停止传播。
You should have a look at the click outside plug in. Basically what's it's doing is setting a click event on the body element and then comparing the event target to see if it's equal to the selector you need and stopping propagation from there.