这是我的代码段。但是内部for循环后代码正在破碎。但没有得到错误消息。 有什么想法吗?
感谢。
var lastnames = document.getElementsByClassName('box_nachname');
var firstnames = document.getElementsByClassName('box_vorname');
var teilnehmer = document.getElementsByClassName('select');
observers = [];
// iterate over nachname array.
for (var i = 0; i < lastnames.length; i++) {
// Create an observer instance.
observers[i] = new Observer();
// Subscribe oberser object.
for(idx in teilnehmer) {
if(teilnehmer[idx].id.split("_")[0].toLowerCase() !== "zl") {
var anynum = function(element) {
observers[i].subscribe(element, updateTeilnehmerSelectbox);
}(teilnehmer[idx]);
}
}
//on blur the Observer fire the updated info to all the subscribers.
var anynumNachname = function(j, element, value, observer) {
cic.addEvent(lastnames[j], 'blur', observer.fire(element, value));
} (i, lastnames[i], lastnames[i].value, observers[i]);
cic.addEvent(firstnames[i], 'blur', function(element, value, observer) {observer.fire(element, value)}(lastnames[i], lastnames[i].value, observers[i]));
}
答案 0 :(得分:2)
您正在“addEvent”调用中使用循环变量“i”。这将无法正常工作,因为每个事件处理程序将共享相同的“i”,因此每个只会看到“i”设置为的最后一个值。
cic.addEvent(firstnames[i], 'blur', (function(index) {
return function(element, value, observer) {
observer.fire(element, value)}(lastnames[index], lastnames[index].value, observers[index]);
};
})(i));
另外,虽然我不确定这是否有必要,但我会在括号中添加你要求“anynumNachname”的函数:
var anynumNachname = (function(j, element, value, observer) {
cic.addEvent(lastnames[j], 'blur', observer.fire(element, value));
})(i, lastnames[i], lastnames[i].value, observers[i]);