e.preventDefault() not bulletproof?

余生颓废 提交于 2019-12-06 04:36:37

I am expecting that the click event is never never never fired (because of the hierarchy with which browser should work through the events) [...]

You have wrong expectations of even.preventDefault().

event.preventDefault() prevents the default action that the browser performs for that element/event combination. E.g. submitting a form or following link. It does not prevent any other event handler from being executed.

e.stopPropagation() prevents the event from bubbling up so that event handlers added to ancestors are not executed.


However, you cannot use any of these methods to prevent the handler of a different event to be executed, so setting a flag seems indeed to be the right way to do this.

Right now I am using the following code in most places on my site which works very good and reliable:

var flag = false; 
$("#element").on( 'touchstart click', function() {
    if ( !flag ) {
        flag = true;
        setTimeout( function() {
            flag = false;
        }, 100 ); // someone else recommended 300 here but I use this value

        // action here

    };                
    return false;
} );

PS That is not my invention, but unfortunately I forgot the source because some time has passed.

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