jQuery bind click *ANYTHING* but *ELEMENT*

前端 未结 6 479
死守一世寂寞
死守一世寂寞 2020-12-02 07:24

Say there are some elements floating around, and I\'m trying to do some when I click ANYTHING(divs, body, whatever...) but the one specified (e.g. div#special).

I\'m

6条回答
  •  臣服心动
    2020-12-02 08:04

    To handle the "do this except when this element is clicked" situation, the general approach is to add an event handler to the document which handles the "do this" case, then add another event handler to the "except this" element, which simply prevents the click event bubbling up to the document;

    $('#special').on('click', function(e) {
        e.stopPropagation();
    });
    
    $(document).on('click', function (e) {
     // Do whatever you want; the event that'd fire if the "special" element has been clicked on has been cancelled.
    });
    

    See the event.stopPropagation() documentation. For those of you using versions earlier than jQuery 1.7 (as was the case when this question was asked), you won't be able to use on(); instead simple replace the 2 uses of on() with bind(); the signature in this case is the same.

    Demo here; http://jsfiddle.net/HBbVC/

提交回复
热议问题