jQuery live('click') firing for right-click

跟風遠走 提交于 2019-11-28 03:16:38

问题


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?


回答1:


It's a known issue:

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.

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).

See also this question asked yesterday.




回答2:


I've found a solution - "fix" the the live() code itself.

In the unminified source of jQuery 1.3.2 around line 2989 there is a function called liveHandler(). Modify the code to add one line:

2989:    function liveHandler(event) {
2990:        if (event.type == 'click' && event.button != 0) return true;

This will stop the click events from firing on anything but the left-mouse button. If you particularly wanted, you could quite easy modify the code to allow for "rightclick" events too, but this works for me so it's staying at that.




回答3:


You can actually rewrite it as:

function reattachEvents(){
    $(element).unbind('click').click(function(){
        //do something
    });
}

and call it when you add a new dom element, it should have the expected result (no firing on the right click event).




回答4:


This is an unfortunate consequence of how live is implemented. It's actually uses event bubbling so you're not binding to the anchor element's click event, you're binding to the document's click event.




回答5:


I solved this by using mousedown events. In my situation the distinction between mousedown and click didn't matter.



来源:https://stackoverflow.com/questions/1489817/jquery-liveclick-firing-for-right-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!