JavaScript:为什么关闭不起作用?

时间:2010-12-23 22:13:13

标签: javascript closures

以下代码仅将最后.enter_form input的值分配给最后MYAPP.list[0].responses[MYAPP.score.round].form[key](其中key是唯一不同的内容)。我认为这是因为只有密钥的最后一个值传递给addEntry(),但我无法弄清楚如何解决这个问题。

$('.enter_form input').each(function() {
    var key = $(this).attr('id');
    var val = $(this).val();
    userDict[key] = val;
    MYAPP.list[0].responses[MYAPP.score.round].form = [];
    function addEntry() {
        return function(k) {
            MYAPP.list[0].responses[MYAPP.score.round].form[k] =  {'entry': userDict[k]};
        }(key);
    }
    addEntry();
}

2 个答案:

答案 0 :(得分:2)

您的addEntry函数是多余的,因为每次迭代都已经在自己的范围内运行,因此keyval被正确保留(希望解释有意义)。您插入的数组也会在每次迭代时被覆盖,因此在.each()结束时,您最终会得到一个只有1个值的数组。它也应该是一个对象而不是一个数组,即使id是数字的。

// you where overwriting this each iteration
MYAPP.list[0].responses[MYAPP.score.round].form = {};

$('.enter_form input').each(function() {

    var el= $(this); // cache instead of creating a new jQuery object each time
    var key = el.attr('id');
    var val = el.val();

    userDict[key] = val;
    MYAPP.list[0].responses[MYAPP.score.round].form[key] =  {'entry': userDict[key]};

}); // ); was also missing

应该工作。

答案 1 :(得分:0)

要弄清楚它的意图有点困难,但我认为这可能是:

MYAPP.list[0].responses[MYAPP.score.round].form = [];
$('.enter_form input').each(function() {
    var $this = $(this),
        key = this.id,
        val = $this.val();
    userDict[key] = val;
    MYAPP.list[0].responses[MYAPP.score.round].form[key] = {
        'entry': val
    };
});

这是基于你的说法“...... key是唯一不同的东西”(大概$(this).val()也有所不同,但我接受了你的观点)。它会为每个表单的MYAPP.list[0].responses[MYAPP.score.round].form input添加id条目,并将其添加到userDict地图。

作为旁注,如果id元素上的input值不是纯数字,那么我怀疑您想要以空白对象开头:< / p>

MYAPP.list[0].responses[MYAPP.score.round].form = {};
//                                                ^^-- change is here

...而不是一个空数组:

MYAPP.list[0].responses[MYAPP.score.round].form = [];

...虽然因为数组是对象,所以即使你要添加非数字属性也能正常工作。


偏离主题:无需$(this).attr('id')。只需使用this.id

相关问题