在“Facebox”中定位元素 盒子
这是我的链接:
如果您单击 test.php 中的链接,它在使用 jquery 'facebox' 脚本的模式框中打开。
我正在尝试对此框中的单击事件进行操作,如果您查看 test.php 的源代码,您将看到我试图在模式框中查找链接的位置。
$('#facebox .hero-link').click(alert('click!'));
然而,它没有检测到点击,奇怪的是,点击事件在页面加载时运行。
然而,关闭按钮确实有一个内置的单击事件来关闭该框,我怀疑我的本地单击事件以某种方式被阻止,但我无法弄清楚。
有人可以帮忙吗? 通常这是一个项目的最后一部分,它阻碍了我,就像往常一样;)
Heres my link:
If you click on the link in test.php, it opens in a modal box which is using the jquery 'facebox' script.
I'm trying to act upon a click event in this box, and if you view source of test.php you'll see where I'm trying to loacte the link within the modal box.
$('#facebox .hero-link').click(alert('click!'));
However, it doesn't detect a click and oddly enough the click event runs when the page loads.
The close button DOES however have a click event built in that closes the box, and I suspect my home-grown click event is being prevented somehow, but I can't figure it out.
Can anyone help? Typically its the very last part of a project and its holding me up, as is always the way ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您收到文档加载警报的原因是
#click
方法采用函数作为参数。 相反,您向其传递了alert
的返回值,该值立即显示警报对话框并返回 null。事件绑定不起作用的原因是在文档加载时,
#facebox .hero-link
尚不存在。 我认为你有两个选择可以帮助你解决这个问题。选项1)仅在facebox显示后绑定点击事件。 例如:
选项 2)研究使用 jQuery Live Query 插件< /强>
当 jQuery Live Query 识别出 Facebox 修改了 DOM 时,它会自动绑定点击事件。 然后你应该只需要这样写:
First, the reason you're getting the alert on document load is because the
#click
method takes a function as an argument. Instead, you passed it the return value ofalert
, which immediately shows the alert dialog and returns null.The reason the event binding isn't working is because at the time of document load,
#facebox .hero-link
does not yet exist. I think you have two options that will help you fix this.Option 1) Bind the click event only after the facebox is revealed. Something like:
Option 2) Look into using the jQuery Live Query Plugin
jQuery Live Query will automatically bind the click event when it recognizes that Facebox modified the DOM. You should then only need to write this:
或者使用事件委托
这基本上将事件挂钩到容器而不是每个元素,并查询容器事件中的 event.target 。
它有多种好处,可以减少代码噪音(无需重新绑定),也更容易占用浏览器内存(dom 中绑定的事件更少)
快速示例 此处
用于轻松事件委托的 jQuery 插件
P.S 事件委托预计将在即将推出的下一个版本 (1.3) 中出现。
Alternatively use event delegation
This basically hooks events to containers rather than every element and queries the event.target in the container event.
It has multiple benefits in that you reduce the code noise (no need to rebind) it also is easier on browser memory (less events bound in the dom)
Quick example here
jQuery plugin for easy event delegation
P.S event delegation is pencilled to be in the next release (1.3) coming very soon.