0

我有这个 Javascript 变量:

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());
       });
}

无法在键数组中推送任何数据,我收到消息:无法调用未定义的方法“推送”

任何想法 ?

4

3 回答 3

7

jQuery 将this回调中的 DOM 元素设置为.each. 您可以保存this到变量中,然后使用它。

var self = this;
$("#item_key div input").each(function(index) {
  self.keys.push($(this).val()));
}
于 2013-05-01T12:18:20.493 回答
1

试试这样:

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

您的代码不起作用,因为this每个循环内部实际上是对输入标签的引用。但是您需要在此处引用Item_properties

于 2013-05-01T12:18:32.303 回答
0

虽然其他两个答案都可以,但这是另一种方法。

您可以使用

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

代替

this.keys.push($(this).val());
于 2013-05-01T14:10:13.863 回答