我是 JavaScript 新手。我有 6 个元素,我想配备非常相似的事件侦听器。我有一个我想改进的可行的蛮力解决方案,但是(我认为)我在 JavaScript 闭包方面遇到了麻烦。
工作代码:
elem = document.getElementById("court1button");
elem.addEventListener("click", wassern_id1, false);
elem = document.getElementById("court1xbutton");
elem.addEventListener("click", abbrechen_id1, false);
elem = document.getElementById("court2button");
elem.addEventListener("click", wassern_id2, false);
elem = document.getElementById("court2xbutton");
elem.addEventListener("click", abbrechen_id2, false);
... 4 more times ...
function wassern_id1(event) {
wassern(1, event)
}
function wassern_id2(event) {
wassern(2, event)
}
... 4 more times ...
function abbrechen_id1(event) {
abbrechen(1, event)
}
function abbrechen_id2(event) {
abbrechen(2, event)
}
... 4 more times ...
function wassern(id, event) { ...
function abbrechen(id, event) { ...
当我找到https://stackoverflow.com/a/2520602/2536029并了解它为什么无法工作时,我的一个简单循环不起作用。然后我想出了以下代码,它也不起作用,但现在我不再明白为什么它不起作用了。有人可以向我解释并帮助我创建工作代码吗?
for (var id = 1; id <= 6; id++) {
elem = document.getElementById("court" + id + "button");
elem.addEventListener(
"click",
function(id2, event2){
wassern(id2, event2);
}(id, event),
false
);
elem = document.getElementById("court" + id + "xbutton");
elem.addEventListener(
"click",
function(id2, event2){
abbrechen(id2, event2);
}(id, event),
false
);
}
PS:问题是,event
在调用期间未定义
function wassern(id, event) { ... event.stopPropagation();