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

偶尔善良 提交于 2019-11-29 09:52:33
Crescent Fresh

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.

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.

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

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.

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

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