jQuery-使用每个

jQuery-使用每个,jquery,object,each,Jquery,Object,Each,我是jQuery的新手 我有一个包含n行的简单表单(尽管我没有使用html表单): 单击按钮时,我想向用户的数据中添加一组城市(假设我们正在与John合作,因此他是[0]) 我希望对象看起来像: { "username": "John", "year": 1999, "cities": [ { "City1": $('.line input).val() }, ... and so on for the 3 cities entered ] } 我试着用 $.

我是jQuery的新手

我有一个包含n行的简单表单(尽管我没有使用html表单):

单击按钮时,我想向用户的数据中添加一组城市(假设我们正在与John合作,因此他是[0])

我希望对象看起来像:

{ "username": "John",
  "year": 1999,
  "cities": [
    { "City1": $('.line input).val() },
    ... and so on for the 3 cities entered
  ]   
}
我试着用

$.each($('.line'), function() { 
   // but I'm not really sure what to put here 
});
谢谢

试试这个

var cities = [];

var $this, input, text, obj;
$('.line').each(function() { 
   $this = $(this);
   $input = $this.find("input");
   text = $this.text();
   obj = {};
   obj[text] = $input.val();
   cities.push(obj);
});

users[0].cities = cities;

何时将城市列表添加到对象?John是否会单击“保存”或“提交”按钮,或者您是否需要在他键入内容时对其进行更新,或者执行其他操作?单击“添加您的城市”按钮时。没什么特别的。你不应该在你的局部变量上使用
var
吗?如果我在每个循环中定义它,它们将为每个不需要的迭代定义。由于这个原因,我在循环之外定义了它们。尽管@marc的解决方案更加优雅,但我最终还是使用了这个解决方案。我相信它更通用,对更多人会有帮助。顺便说一句,在我看来,这只是将对象
obj
的引用传递给数组,这意味着对象中的数据会被覆盖。。。我认为…应该是
var cities=new Array()而不是
var cities=[]
因为后者不允许您使用它。错误将显示说
.push
不是有效的方法。
$.each($('.line'), function() { 
   // but I'm not really sure what to put here 
});
var cities = [];

var $this, input, text, obj;
$('.line').each(function() { 
   $this = $(this);
   $input = $this.find("input");
   text = $this.text();
   obj = {};
   obj[text] = $input.val();
   cities.push(obj);
});

users[0].cities = cities;
$.each($('.line'), function() { 
   var key = $(this).text().replace(/.*(City\d+).*/,'$1');
   user.cities[key] = $(this).find('input').val(); 
});