没有jQuery的stopPropagation [英] stopPropagation without jQuery

查看:55
本文介绍了没有jQuery的stopPropagation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绑定到一个链接(通过使用jQuery的 .live()函数)点击事件然后使用纯JS和HTML手动添加 onclick 事件处理程序(如< a href =...... onclick =some action> ; )。我想防止事件冒泡到 live 方法,但我不知道如何。

I bind to a link (by using the .live() function of jQuery) click event and then manually add an onclick event handler with pure JS and HTML (like <a href="".... onclick="some action">). I want to prevent bubbling of the event to the live method but I don't know how.

可能 e.stopPropagation()在这种情况下很有用,但事件处理程序添加了 onclick 是用纯JS编写的,我无法从jQuery元素包装器外部调用 stopPropagation()返回false 在这种情况下不起作用。我试图用 $替换 return false 。事件('click')。stopPropagation()但我认为这是错误,因为它不起作用。

Maybe e.stopPropagation() is helpful in this situation but the event handler added with onclick is written in pure JS and I can't call stopPropagation() from outside the jQuery element wrapper. return false in this situation does not work. I tried to substitute return false with $.Event('click').stopPropagation() but I think this is wrong as it did not work.

如何防止冒充 live()没有jQuery包装器的方法?

How to prevent bubling to live() method without jQuery wrapper?

推荐答案

使用 .live ,你无法阻止传播。这是因为使用 .live ,事件处理程序绑定到DOM树的根。因此,在调用处理程序之前,事件必须冒泡到最高元素。关于使用 .live 的注意事项之一。

With .live, you cannot stop propagation. This is because with .live, the event handler is bound to the root of the DOM tree. Hence the event must bubble upto the highest element before your handler can be called. Its one of the caveats on using .live.

考虑使用。委托(如果您希望处理程序保持不变)或使用。绑定

Consider using .delegate (if you want the handler to persist) or use .bind instead.

如果要完全禁用实时处理程序,请使用die:

If you want the live handler to be disabled completly, use die:

$("#myHref").die("click", aClick); // this will remove any existing event handlers
$("#myHref").click(yourhandler);   // add your handler

演示1:JsFiddle 1

或者,添加内联处理程序(并从那里取消事件):

Or, add an inline handler (and cancel the event from there):

<a href=".." onclick="yourhandler">

演示2:JsFiddle 2

在任何jquery事件处理程序之前,将首先调用内联处理程序。

Inline handlers will be called first always before any jquery event handlers.

这篇关于没有jQuery的stopPropagation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆