如何仅从执行事件的 div 中删除事件
How to remove an event from only one div on which event is performed
let popped = 0;
document.addEventListener('click', function(e){
if (e.target.className === "balloon"){
e.target.style.backgroundColor = "#ededed";
e.target.textContent = "POP!";
popped++;
removevent(e);
checkAllPopped();
}
});
function removevent(e) {
e.target.removeEventListener('click',function() {})
}
我试图在用户点击 div 后删除该事件。但无论我如何尝试放置 removeEventListenever,它都不起作用。我尝试使用自定义函数来完成它,例如:
function abc(e) {
//some code
}
document.addEventListener('click',abc,true)
document.removeEventListener('click',abc,true)
不过,这也没有成功。
如果您想根据具体情况删除事件侦听器,请考虑为每个气球添加单独的事件侦听器。然后,在处理程序函数中,您可以在每个气球“弹出”时将其从中移除。
let popped = 0;
const balloons = document.querySelectorAll('.balloon');
function handler(e){
if (e.target.className === "balloon"){
e.target.style.backgroundColor = "#ededed";
e.target.textContent = "POP!";
popped++;
console.log(popped);
e.target.removeEventListener('click', handler);
}
}
for (let balloon of balloons) {
balloon.addEventListener('click', handler);
}
<div class="balloon">Balloon</div>
<div class="balloon">Balloon</div>
<div class="balloon">Balloon</div>
<div class="balloon">Balloon</div>
<div class="balloon">Balloon</div>
let popped = 0;
document.addEventListener('click', function(e){
if (e.target.className === "balloon"){
e.target.style.backgroundColor = "#ededed";
e.target.textContent = "POP!";
popped++;
removevent(e);
checkAllPopped();
}
});
function removevent(e) {
e.target.removeEventListener('click',function() {})
}
我试图在用户点击 div 后删除该事件。但无论我如何尝试放置 removeEventListenever,它都不起作用。我尝试使用自定义函数来完成它,例如:
function abc(e) {
//some code
}
document.addEventListener('click',abc,true)
document.removeEventListener('click',abc,true)
不过,这也没有成功。
如果您想根据具体情况删除事件侦听器,请考虑为每个气球添加单独的事件侦听器。然后,在处理程序函数中,您可以在每个气球“弹出”时将其从中移除。
let popped = 0;
const balloons = document.querySelectorAll('.balloon');
function handler(e){
if (e.target.className === "balloon"){
e.target.style.backgroundColor = "#ededed";
e.target.textContent = "POP!";
popped++;
console.log(popped);
e.target.removeEventListener('click', handler);
}
}
for (let balloon of balloons) {
balloon.addEventListener('click', handler);
}
<div class="balloon">Balloon</div>
<div class="balloon">Balloon</div>
<div class="balloon">Balloon</div>
<div class="balloon">Balloon</div>
<div class="balloon">Balloon</div>