jQuery stopPropagation not working

我只是一个虾纸丫 提交于 2020-01-03 16:40:29

问题


I'm using the following color picker and it works fine, but when i click on the color picker icon, i don't want it to bubble to body. So i tried the following and now the color picker is not working.

Check http://jsfiddle.net/CWGgM/.

If you remove the below code from jsfiddle then it works. What is causing this

$('#test').click(function(e){
    e.stopPropagation();
});

回答1:


It appears to use its own live() style code, where events are allowed to bubble up and are handled on the document.

Therefore, the events must propagate to document or they won't work.

You could avoid the event triggering on body with the following workaround...

$('body').click(function(event) {
    if ($(event.target).parent()[0] == $('.mColorPickerTrigger')[0]) {
       return true;   
    }
});

jsFiddle.

Or this might work better with multiple color pickers...

$('body').click(function(event) {
    if ($(event.target).parent().hasClass('mColorPickerTrigger')) {
       return true;   
    }
});

jsFiddle.




回答2:


Like @alex mentioned it, the color picker seems to be listening clicks on the whole document using live(). Before blocking the propagation, you can check if the event originated from the color picker, and let it bubble up if it did. You need to use closest(), because it's possible to click either on the color picker icon's <span> container or the <img> element inside.

$('#test').click(function(e){
    if($(e.target).closest('.mColorPickerTrigger').length) return;
    e.stopPropagation();
});

Check out the jsfiddle demo: http://jsfiddle.net/CWGgM/1/



来源:https://stackoverflow.com/questions/6054136/jquery-stoppropagation-not-working

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