jQuery live('click') 触发右键单击

jQuery live(#39;click#39;) firing for right-click(jQuery live(click) 触发右键单击)

本文介绍了jQuery live('click') 触发右键单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 jQuery 中 live() 函数的一个奇怪行为:

I've noticed a strange behaviour of the live() function in jQuery:

<a href="#" id="normal">normal</a>
<a href="#" id="live">live</a>

$('#normal').click(clickHandler);
$('#live').live('click', clickHandler);

function clickHandler() {
    alert("Clicked");
    return false;
}

在您右键单击实时"链接并触发处理程序,然后不显示上下文菜单之前,这很好而且很花哨.事件处理程序根本不会在正常"链接上触发(如预期的那样).

That's fine and dandy until you right-click on the "live" link and it fires the handler, and then doesn't show the context menu. The event handler doesn't fire at all (as expected) on the "normal" link.

我已经能够通过将处理程序更改为此来解决它:

I've been able to work around it by changing the handler to this:

function clickHandler(e) {
    if (e.button != 0) return true;
    // normal handler code here
    return false;
}

但是必须将它添加到所有事件处理程序中真的很烦人.有没有更好的方法让事件处理程序只像常规点击处理程序一样触发?

But that's really annoying to have to add that to all the event handlers. Is there any better way to have the event handlers only fire like regular click handlers?

推荐答案

这是一个已知问题:

似乎 Firefox 没有触发a 上元素的单击事件右键单击,虽然它会触发mousedown 和 mouseup.然而,它确实document 上触发点击事件!由于 .live 捕获文档级别的事件,它看到甚至元素的点击事件尽管元素本身没有.如果您使用 mouseup 之类的事件,两者p 元素和 document将看到该事件.

It seems like Firefox does not fire a click event for the element on a right-click, although it fires a mousedown and mouseup. However, it does fire a click event on document! Since .live catches events at the document level, it sees the click event for the element even though the element itself does not. If you use an event like mouseup, both the p element and the document will see the event.

您的解决方法是目前您能做的最好的.它似乎只影响 Firefox(我相信它实际上是 Firefox 中的一个错误,而不是 jQuery 本身).

Your workaround is the best you can do for now. It appears to only affect Firefox (I believe it's actually a bug in Firefox, not jQuery per se).

另请参阅 此问题昨天.

这篇关于jQuery live('click') 触发右键单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:jQuery live('click') 触发右键单击

基础教程推荐