2013-05-01 71 views
0

我有此Javascript變量:如何將數值從一個jQuery函數內推到一個數組

var Item_properties = { 
    id : null, 
    keys : [], 
    hydrate: function() { 
     //get data 
     this.id = $('input[id=id]').val(); 

     $("#item_key div input").each(function(index) { 
      this.keys.push($(this).val()); 
     }); 
} 

這是不可能的按鍵陣列將任何數據,我得到的消息: 不能打電話方法'推'未定義

任何想法?

回答

7

jQuery將this設置爲回調到.each的DOM元素。您可以將this保存到一個變量中,然後使用它。

var self = this; 
$("#item_key div input").each(function(index) { 
    self.keys.push($(this).val())); 
} 
1

嘗試這樣的:因爲this

var $this = this; 
$("#item_key div input").each(function (index) { 
    $this.keys.push($(this).val()); 
}); 

你的代碼沒有工作的每一個循環內實際上參考輸入標籤。但您需要在此處參考Item_properties

0

雖然two其他answers沒問題,但這是另一種方法。

您可以使用

Item_properties.keys.push($(this).val()); 

而不是

this.keys.push($(this).val()); 
相關問題