admin管理员组

文章数量:1242850

I was wondering if there was any way to add an event listener to the whole page except one div in it. To be more specific in the example below is there any way to add an event listener to the body except the div? e.g

html:

<body>
 <div class="sssss"></div>
</body>

I was wondering if there was any way to add an event listener to the whole page except one div in it. To be more specific in the example below is there any way to add an event listener to the body except the div? e.g

html:

<body>
 <div class="sssss"></div>
</body>

Share Improve this question asked Nov 13, 2019 at 12:20 shauna vayneshauna vayne 1691 gold badge2 silver badges12 bronze badges 5
  • 1 The event listener is always only attached to the element you call addEventListener on. Please try to give more detail as of what you need to do. – connexo Commented Nov 13, 2019 at 12:22
  • 1 Check if the event.target has the class sssss. If yes, then just do nothing. – Andreas Commented Nov 13, 2019 at 12:23
  • @Andreas Given the current level of information provided, that is just a guess. OP needs to clarify their needs. Not processing the event is one approach; another one could be to prevent the propagation of the relevant event on div.sssss. – connexo Commented Nov 13, 2019 at 12:24
  • You can create bunch of if in event's callback function to perform action on specific elements. i believe, there is no direct way to eliminate child elements from attaching event. (correct me if i am wrong) – Ishu Commented Nov 13, 2019 at 12:31
  • Again, your question lacks essential information to be answered. Please fix that. – connexo Commented Nov 13, 2019 at 15:10
Add a ment  | 

3 Answers 3

Reset to default 10

Check the targets class name.

document.body.addEventListener('click', function(e) {
    if (!e.target.classList.contains('sssss')) {
        // your code
    }
});

you can do this using JQuery : html :

<body id='myBody'>
    <div id='noActionDiv'></div>
</body>

javascript:

$("#myBody").click(function(e){
    var myID = e.target.id;
    if(myID!='noActionDiv'){
        //your action here
    }
});

addEventlistener has to be called for each element individually.

See: https://developer.mozilla/en-US/docs/Web/API/EventTarget/addEventListener

Here is an example of how to attach an event listener to all elements within the body element excluding the ones with the class "sssss":

// define callback function once to avoid memory issues
function processEvent(e){
  /* do something */
}
// get all elements except those with class sssss
const elements = document.querySelectorAll('body *:not(.sssss)');
for(i=0 ; i < elements.length; i++){
  elements[i].addEventListener('click', processEvent, false);
}

本文标签: javascriptaddEventListener to the whole body of a page except one divStack Overflow