我试图将事件监听器添加到所有对象,除了几个选定的(选定的也有任意级别的任意子元素)?
我以前问过这个问题,但我真的没有得到答案。我差一点就解决了。你能帮我调试一下吗?我将向名为bodylistener
的主体元素添加一个事件侦听器,并向名为selectedElementsMarkTrue
的几个选定元素添加一个事件侦听器。我不想执行一些代码的几个选定元素,侦听器selectedElementsMarkTrue
在setTimeout function
之前执行bodylistener
。selectedElementsMarkTrue
将变量selectedElements
设置为true
, bodylistener
在执行一些代码之前检查selectedElements
是否为true
。我的代码仍然有问题:
var selectedElements = false;
var bodylistener = function(){
window.setTimeout(function(){//Setting timeout so that the other handler, selectedElementsMarkTrue, always performs first
(function(){
if(selectedElements == false){
//Do some stuff
}else{
selectedElements = false;
}
});
}, 10);//Could be 0, but te be sure I set 10
};
var selectedElementsMarkTrue = function(){
selectedElements = true;
};
$('#dontAddEventListener1, #dontAddEventListener2').each(function(){
this.addEventListener('click', selectedElementsMarkTrue, false);
});
document.body.addEventListener('click', bodylistener, false);
我不能得到setTimeout
函数执行底层代码?
听起来你想要这样的行为:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.addEventListener("DOMContentLoaded", function() {
document.body.addEventListener("click", function(e) {
var el = e.target;
do {
if (el.hasAttribute && el.hasAttribute("data-nofire")) {
return;
}
} while (el = el.parentNode);
alert('do stuff');
}, true);
}, false);
</script>
</head>
<body>
<p><span>click me</span></p>
<p data-nofire><span>click me</span></p>
<p data-nofire>click me</p>
<p>click me</p>
</body>
</html>
或者,你可以像Naren建议的那样做:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.addEventListener("DOMContentLoaded", function() {
var nofire = document.getElementsByClassName("nofire");
for (var i = 0; i < nofire.length; ++i) {
nofire[i].addEventListener("click", function(e) {
e.stopPropagation();
}, true);
}
document.body.addEventListener("click", function(e) {
alert('do stuff');
}, false);
}, false);
</script>
</head>
<body>
<p><span>click me</span></p>
<p class="nofire"><span>click me</span></p>
<p class="nofire">click me</p>
<p>click me</p>
</body>
</html>
通过处理元素来防止事件传播点击事件
$('#dontAddEventListener1, #dontAddEventListener2').click( function(event){ event.preventDefault(); return false; });