我在for循环中创建了以下p元素。单击此特定元素时,我希望将单个元素传递给下面的方法,但事实并非如此。整个元素数组都通过了。有人可以帮忙吗?
for (var i = 0; i < data.length-1; i++) {
var stuff= document.createElement("p");
stuff.onclick = methodA(stuff);
}
function methodA(self){
var id = self.id;
var myemail= id;
}
我试过
stuff.onclick = methodA(this);
它也无效
答案 0 :(得分:0)
您实际上正在调用方法methodA
并将该调用的结果分配给onclick
。相反,我相信你的意图是创建一个闭包,以便在点击时调用methodA
。像这样:
var data = [1, 2, 3, 4, 5];
for (var i = 0; i < data.length - 1; i++) {
var stuff = document.createElement("p");
stuff.appendChild(document.createTextNode("p #" + i));
// Using a closure
stuff.onclick = (function(cStuff){ return function() { methodA(cStuff); } })(stuff);
// Or instead you could use 'bind'
// stuff.onclick = methodA.bind(null, stuff);
document.body.appendChild(stuff);
}
function methodA(self) {
var id = self.id;
var myemail = id;
}