开发者

jQuery stopPropagation not working

开发者 https://www.devze.com 2023-03-06 18:36 出处:网络
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

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();
});


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.


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号