Is there any way to check if bubble triggered the click?

后端 未结 5 1510
谎友^
谎友^ 2020-12-24 06:07

Clicking on elements in jQuery causes bubble up to body. If we have a click handler binded to body that shows an alert, then clicking on any element will bubble up to body a

5条回答
  •  轮回少年
    2020-12-24 06:13

    Compare event.target to this. this is always the event where the handler is bound; event.target is always the element where the event originated.

    $(document.body).click(function(event) {
        if (event.target == this) {
            // event was triggered on the body
        }
    });
    

    In the case of elements you know to be unique in a document (basically, just body) you can also check the nodeName of this:

    $(document.body).click(function(event) {
        if (event.target.nodeName.toLowerCase() === 'body') {
            // event was triggered on the body
        }
    });
    

    You have to do toLowerCase() because the case of nodeName is inconsistent across browsers.

    One last option is to compare to an ID if your element has one, because these also have to be unique:

    $('#foo').click(function(event) {
        if (event.target.id === 'foo') {
            // event was triggered on #foo
        }
    });
    

提交回复
热议问题