以下代码是该事件的实际练习:
第三次点击后,Handler1被移除,但我认为当用户第四次点击时,应该再次添加处理程序1。但是,通过几次实验,我发现如果一个事件处理程序被" removeEventListener"删除,那么该侦听器就不能再被添加回来。我的问题是,是否可以在Javascript中再次向事件添加一个监听器?
<!doctype html>
<html>
<body>
<button id="btn1">Click me</button>
<script>
var count = 0;
function countClick() {
count++;
}
function handler1() {
alert("Handler 1 has been triggered " + count + " times!");
}
function handler2() {
alert("Handler 2 has been triggered " + count + " times!");
if(count == 3) {
btn1.removeEventListener("click", handler1);
}
}
var btn1 = document.getElementById("btn1");
btn1.addEventListener("click", countClick);
btn1.addEventListener("click", handler1);
btn1.addEventListener("click", handler2);
</script>
</body>
</html>
&#13;
答案 0 :(得分:0)
var count = 0;
function countClick() {
count++;
}
function handler1() {
alert("Handler 1 has been triggered " + count + " times!");
}
function handler2() {
alert("Handler 2 has been triggered " + count + " times!");
if (count == 3) {
btn1.removeEventListener("click", handler1);
}
if (count == 4) {
btn1.addEventListener("click", handler1);
}
}
var btn1 = document.getElementById("btn1");
btn1.addEventListener("click", countClick);
btn1.addEventListener("click", handler1);
btn1.addEventListener("click", handler2);
&#13;
<body>
<button id="btn1">Click me</button>
</body>
&#13;