将事件添加到循环内的元素-JScript /结束语

将事件添加到循环内的元素-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.