[英]JavaScript: Why isn't my closure working?
以下代碼僅將最后一個.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();
}
你的addEntry函數是多余的,因為每次迭代都已在你自己的范圍內運行,所以key
和val
被正確保存(希望解釋有意義)。 您插入的數組也會在每次迭代時被覆蓋,因此在.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
應該管用。
確定要執行的操作有些困難,但我認為可能是這樣:
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()
也有所不同,但我接受了你的觀點)。 它將為表單的每個input
id
添加到MYAPP.list[0].responses[MYAPP.score.round].form
條目,並將它們添加到userDict
映射。
作為旁注,如果input
元素上的id
值不是純數字,那么我懷疑你想要一個空白對象 :
MYAPP.list[0].responses[MYAPP.score.round].form = {};
// ^^-- change is here
...而不是一個空數組:
MYAPP.list[0].responses[MYAPP.score.round].form = [];
...盡管由於數組是對象,所以即使您添加非數字屬性也可以使用。
離題 :不需要$(this).attr('id')
。 只需使用this.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.