使用 for 循环附加 onclick 方法 [英] Append onclick method using for loop
问题描述
我将 onclick 事件附加到我动态创建的元素.我正在使用下面的代码,这只是重要的部分.
I'm appending onclick events to elements that I'm creating dynamically. I'm using the code below, this is the important part only.
Test.prototype.Show= function (contents) {
for (i = 0; i <= contents.length - 1; i++) {
var menulink = document.createElement('a');
menulink.href = "javascript:;";
menulink.onclick = function () { return that.ClickContent.apply(that, [contents[i]]); };
}
}
首先它说它是未定义的.然后我改了加:
First it says that it's undefined. Then I changed and added:
var content = content[i];
menulink.onclick = function () { return that.ClickContent.apply(that, [content]); };
现在发生的事情是它总是将最后一个元素附加到所有 onclick 事件(又名元素).我在这里做错了什么?
What is happening now is that it always append the last element to all onclick events( aka elements). What I'm doing wrong here?
推荐答案
这是一个经典问题.当回调被调用时,循环结束,所以 i
的值为 content.length
.
It's a classical problem. When the callback is called, the loop is finished so the value of i
is content.length
.
例如:
Test.prototype.Show= function (contents) {
for (var i = 0; i < contents.length; i++) { // no need to have <= and -1
(function(i){ // creates a new variable i
var menulink = document.createElement('a');
menulink.href = "javascript:;";
menulink.onclick = function () { return that.ClickContent.apply(that, [contents[i]]); };
})(i);
}
}
这个立即调用的函数为新变量 i
创建了一个作用域,其值因此受到保护.
This immediately called function creates a scope for a new variable i
, whose value is thus protected.
更好的是,将处理程序的代码分离成一个函数,既是为了清晰起见,也是为了避免不必要地创建和丢弃构建器函数:
Better still, separate the code making the handler into a function, both for clarity and to avoid creating and throwing away builder functions unnecessarily:
Test.prototype.Show = function (contents) {
for (var i = 0; i <= contents.length - 1; i++) {
var menulink = document.createElement('a');
menulink.href = "javascript:;";
menulink.onclick = makeHandler(i);
}
function makeHandler(index) {
return function () {
return that.ClickContent.apply(that, [contents[index]]);
};
}
};
一种完全避免这个问题的方法,如果你不需要 与IE8的兼容性,就是用forEach
引入作用域,而不是使用for
循环:
A way to avoid this problem altogether, if you don't need compatibility with IE8, is to introduce a scope with forEach
, instead of using a for
loop:
Test.prototype.Show = function (contents) {
contents.forEach(function(content) {
var menulink = document.createElement('a');
menulink.href = "javascript:;";
menulink.onclick = function() {
return that.ClickContent.call(that, content);
};
});
}
这篇关于使用 for 循环附加 onclick 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!