0

我发现了一些似乎与此相关的问题,但在我的理解范围内,我的问题有所不同,所以就这样吧。我已经大大简化了我的代码,甚至用注释替换了一行,但概念是一样的......

function myFunction(options) {
    var button;
    options.widgets.forEach(function (w) {
        button = document.createElement("button");
        //add button to the DOM
        aListOnMyPage.addEventListener("selectionchanged", function (args) {
            var a = button;
        });
    });
}

因此,对于每个小部件,我将创建一个新对象,然后将事件侦听器添加到页面上的列表中,该列表的函数需要引用我创建的 DOM 元素(按钮)。我看到的行为是我的按钮在我创建事件侦听器的位置正确设置,但是当侦听器的事件触发时,按钮始终是对我创建的最后一个按钮的引用。也许是因为已经晚了,但我无法理解为什么会这样。任何人都可以为我澄清这一点吗?

4

2 回答 2

3

当然可以。

您的问题实际上是范围。让我们看一下您编写的代码:

function myFunction(options) {
    var button;
    options.widgets.forEach(function (w) {
        button = document.createElement("button"); // UH-OH...
        //add button to the DOM
        aListOnMyPage.addEventListener("selectionchanged", function (args) {
            var a = button;
        });
    });
}

注意哦?您已经声明了button应该等于document.createElement("button"),但由于您没有使用var关键字,因此您声明了一个全局变量,而不是多个局部变量。这意味着每次您的循环运行时,您的侦听器都会引用一个全局变量,这会导致您的问题。

确保在此处使用局部变量,如下所示:

function myFunction(options) {
    options.widgets.forEach(function (w) {
        var button = document.createElement("button"); 
        //add button to the DOM
        aListOnMyPage.addEventListener("selectionchanged", function (args) {
            var a = button;  
        });
    });
}

这应该会大大改善您的情况。至少,我希望它能帮助你更进一步。祝你好运。

于 2012-08-25T06:49:06.283 回答
1

I think you are facing this problem because of closures, the button variable used throughout you’re myFunction is same, all changes are reference changes, so I think changing the declaration of the variable to inside the anonymous function should solve this problem.

function myFunction(options) {
    //var button;
    options.widgets.forEach(function (w) {
        var button = document.createElement("button");
        //add button to the DOM
        aListOnMyPage.addEventListener("selectionchanged", function (args) {
            var a = button;
        });
    });
}

this change provides the anonymous function in forEach with separate button variables.

于 2012-08-25T06:55:16.807 回答