我是JavaScript新手。我有6个元素,我想配备非常相似的事件监听器。我有一个工作强力解决方案,我想改进,但(我认为)我有Java Script关闭的麻烦。
工作代码:
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();
答案 0 :(得分:8)
你需要将事件监听器机制放在闭包中,在内部函数的外行闭包返回值中,你希望你的事件监听器应该在循环执行或范围完成后出现。
你需要将整个事件或getElementByid
封装在内部,这里是代码片段
for (var id = 1; id <= 2; id++) {
(function(id){
elem = document.getElementById("court" + id + "button");
elem.addEventListener(
"click",
function(event){wassern(id, event);},
false
);
elem = document.getElementById("court" + id + "xbutton");
elem.addEventListener(
"click",
function(event){abbrechen(id, event);},
false
);
})(id)
}
要获取可以传递此事件的事件,请参阅addEventListner
这是jsFiddle代码http://jsfiddle.net/Xtgr4/
希望以上回答对你有意义