jQuery on click on everything but a div and it's children

前端 未结 4 484
时光取名叫无心
时光取名叫无心 2021-01-11 18:38

I want to do something when I click anywhere, except when I click a div and it\'s children. This is what I\'ve tried so far, but it\'s not working (clicking on it\'s childr

相关标签:
4条回答
  • 2021-01-11 19:17

    Use not with a comma to have both selectors: the element itself and the elements children

    jQuery(document.body).on("click", ":not(#calculator, #calculator *)", function(e){ 
        console.log(this); 
        e.stopPropagation(); 
    });​​​​​​​
    

    jsFiddle

    0 讨论(0)
  • 2021-01-11 19:19

    I don't have enough requirement to add commend, so I need to ask my question here to @epascarello. When I made few children, A and B still affected. I am not sure I am wrong or not, but I really want to get solution.

    jQuery(document.body).on("click", ":not(#calculator, #calculator *)", function(e){ 
        console.log(this); 
        e.stopPropagation(); 
        alert('test');
    });
    

    Live Demo

    0 讨论(0)
  • 2021-01-11 19:22

    Instead of

    $('body').on('click', '* :not(#calculator)',  function(e){
    
    });​
    

    You can use (this version is preferred as it is more performant)

    $("body").on("click", ":not(#calculator, #calculator *)", function(e){ 
    
    });​
    

    or

    $("body :not(#calculator, #calculator *)").on("click", function(e){ 
    
    });​
    
    0 讨论(0)
  • 2021-01-11 19:35

    You could check inside the function for the element in question:

    $('body').click( function(e){
        if (!$(e.target).is("#calculator") || $("#calculator").has(e.target).length ) {
            // do your stuff
        }
    });
    
    0 讨论(0)
提交回复
热议问题