jQuery 传播问题

发布于 2024-12-11 22:53:59 字数 397 浏览 0 评论 0原文

另一个愚蠢的问题,我无法通过所有其他线程完全弄清楚它,所以希望这里有人可以。

演示位于 http://jsfiddle.net/OwenMelbz/PaAt2/

基本上我

when click inside document
spawn div

when click div
do nothing

when doubleclick div
do this

在那一刻,当我双击它时,它确实运行了代码,但它也会在我单击该元素的地方生成另一个 div。

我的代码位于 jsfiddle 上,正如我上面发布的那样!

谢谢

another silly question, i cant quite figure it out via all the other threads so hopefuly someone here can.

a demo is at http://jsfiddle.net/OwenMelbz/PaAt2/

basically ive got it so

when click inside document
spawn div

when click div
do nothing

when doubleclick div
do this

at the moment, when i double click it, it DOES run the code, but it also spawns another div where i click on the element.

my code is on jsfiddle as i posted above!

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

末骤雨初歇 2024-12-18 22:53:59

不知道为什么,但这对我有用。 http://jsfiddle.net/PaAt2/4/。这可能与实时处理事件与绑定的方式有关。

Not sure why but this worked for me. http://jsfiddle.net/PaAt2/4/. It might have to do with how live handles events vs bind.

断舍离 2024-12-18 22:53:59

Keith 是对的,他的解决方案之所以有效,是因为 live() 和 bind() 的工作方式存在差异。

bind() 将事件处理程序附加到调用它的 jQuery 对象中的所有 DOM 元素。 live() 将 jQuery 的事件处理程序附加到“事件上下文”(查找 http://api.jquery.com /live 了解更多信息)。默认情况下,这是 DOM 树的根。该事件处理程序位于捕获其绑定对象内的 DOM 对象冒泡(或传播)的事件。当它捕获一个事件时,它会查看事件的来源,如果它与应用了 live() 的 jQuery 对象的选择器匹配,它就会运行您作为事件处理程序提供的函数参数。

这意味着,如果您有一个容器(在本例中为“#project-wrap”)并绑定到其单击事件,您通常会获得源自该容器内任何内容的点击,因为它们会冒泡到该容器。但是,如果您使用 live() 将事件绑定到容器,您将只能获得源自该容器本身的点击,即从容器内的空白区域点击,而不是点击其中包含的任何内容。

Keith is right that his solution works because of the difference between how live() and bind() work.

bind() attaches your event handler to all the DOM elements in the jQuery object it is called on. live() attaches an event handler from jQuery to the 'Event Context' (look up http://api.jquery.com/live for futher info). By default this is the root of the DOM tree. This event handler sits there catching events that bubble up (or propagate from) DOM objects inside the object it is bound to. When it catches one, it looks at what originated the event and if it matches the selector of the jQuery object to which live() was applied, it runs the function argument you supply as the your event handler.

This means that if you have a container (which is '#project-wrap' in this example) and bind to its click event, you will normally get clicks originating from anything inside that container, because they will bubble up to the container. But if you bind an event to the container using live(), you will only get clicks which originated from that container itself i.e. clicks from empty space within the container, not clicks on anything contained within it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文