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

nic*_*ckf 9 html javascript jquery event-handling

我注意到live()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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Cre*_*esh 9

这是一个众所周知的问题:

看起来Firefox不会在右键单击时触发元素的click事件,尽管它会触发mousedown和mouseup.但是,它 触发点击事件document!由于.live捕获了文档级别的事件,因此它会看到元素的click事件,即使元素本身没有.如果您使用像mouseup这样的事件,则p元素和document 将会看到该事件.

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

另见昨天提出的这个问题.