jquery live() 函数和 AJAX 加载内容的问题
对于我正在实现的交互设计技巧,我对 jquery 有一个小问题。我有一个链接和一个隐藏的下拉菜单,当用户单击该链接时显示。如果用户单击链接或菜单,我希望隐藏下拉菜单。这两个元素都位于使用 AJAX 动态加载的页面部分(因此使用了 live() 函数)。如果我在非 AJAX 重新加载的容器上执行此操作,则一切正常,但一旦它是动态加载的内容,则一切都不起作用(下拉菜单显示,但如果我单击外部则不会隐藏)。我的代码如下:(
$("#clickToOpen").live('click',function(event) {
$("#dropdownMenu").show();
event.stopPropagation();
});
$("#dropdownMenu").live('click',function(event){
event.stopPropagation();
});
$(document).live('click',function() {
$("#dropdownMenu").hide();
});
我还尝试直接使用 click() 函数来处理(文档)上的最后一个事件,因为该元素未重新加载,但不起作用)
有什么想法吗?
i have a little problem with jquery for an interaction design trick i'm implementing. I have a link and a hidden drop-down menu to show when the user clicks on the link. I want the dropdown menu to hide if the user clicks out of the link or menu. Both of these elements are on the portion of a page loaded dynamically with AJAX (hence the use of the live() function). Everything works fine if I do it on a non AJAX-reloaded container, but doesn't work as soon as it's a dynamically loaded content (the dropdown menu shows, but doesn't hide if i click outside). My code is the following:
$("#clickToOpen").live('click',function(event) {
$("#dropdownMenu").show();
event.stopPropagation();
});
$("#dropdownMenu").live('click',function(event){
event.stopPropagation();
});
$(document).live('click',function() {
$("#dropdownMenu").hide();
});
(i also tried with the click() function directly for the last event on (document), since this element is not reloaded, but doesn't work)
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我错了,应该有人纠正我。
但就我对
.live
的理解而言,调用event.stopPropagation()
根本没有任何效果,因为为了使 live 工作,它会附加到窗口或文档对象,因此,它已经传播得尽可能远了。关于隐藏菜单,
我相信您应该考虑添加透明覆盖层,与模式对话框使用的类型相同。
然后,您将绑定到覆盖层以隐藏菜单。
Someone should correct me if I am wrong.
But for my understanding of
.live
callingevent.stopPropagation()
will have no effect at all as, for live to work it is attached to the window or document object, hence, it has propagated as far as it can already.With regards to the hiding the menu,
I believe you should look into adding a transparent overlay, the same sort of thing as modal dialogs use.
Then you are binding to the overlay to hide the menu.
我觉得你可以创建一个类似的类
并使用这样的toggleClass...
不是经过测试的代码...
这是你的最终代码...
i feel you can create a class like
and use a toggleClass like this...
not a tested code...
here is the final code for u ...