将事件添加到循环内的元素-JScript /结束语 [英] Adding events to elements inside loop - JScript/Closures
本文介绍了将事件添加到循环内的元素-JScript /结束语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在建立一个按钮列表,我希望每个按钮都使用当前的 members [member] .id 触发 addForm()函数。
I'm building a list of buttons and I want each one to trigger the addForm() function with the current members[member].id.
但是碰巧只有最后一个按钮会触发该事件。
But it happens that only the last button will fire the event.
我知道它与闭包和如您所见,我已经修改了使用该模式的功能。
I know it has something to do with closures and as you can see I have adapted the function to use this pattern.
我在做什么错了?
function displayConnections(connections) {
/*(...)*/
for (var member in members) {
connectionsDiv.innerHTML += "<p>" + members[member].firstName + " " + members[member].lastName
+ " ID: " + members[member].id;
btn = document.createElement("input");
btn.setAttribute("type","button");
btn.setAttribute("value","Send Message");
btn.setAttribute("id",members[member].id);
btn.onclick = function (id) {
return function () {
addForm(id);
};
}(members[member].id);
connectionsDiv.appendChild(btn);
}
}
谢谢。
推荐答案
好吧,除了这些替代方法,您还可以使用:
Well, instead of those workaround you can also use:
element.setAtrribute('onClick', 'javascript:functionName(' + parameter + ');');
这对我有用,也应该对您有用。
which worked for me and should work for you as well.
这篇关于将事件添加到循环内的元素-JScript /结束语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文