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 classsssss
. 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
3 Answers
Reset to default 10Check the target
s 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
版权声明:本文标题:javascript - addEventListener to the whole body of a page except one div - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740142900a2231235.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论