0

我在一个表单中有多个字段集,它们具有单独的输入/选择元素和以下 JS/jQuery 来处理保存时的元素。

var form = {};

$('fieldset').each(function() {
  var fieldsetId = this.id; var fieldset = {};
  $('#'+fieldsetId+' input:checkbox, #'+fieldsetId+' input:radio').each(function() {
    name = $(this).attr('name');
    fieldset[name] = $(this).val();
  });

  $('#'+fieldsetId+' select').each(function() {
    ...
  }

  form[fieldsetId] = fieldset;
});

正在读取数据。问题在于多个字段集。每个连续的字段集都覆盖最后一个并使用所有先前的输入值。

目前,返回的处理数据看起来像:

first-fieldset (object)
  key:2
  textbox:"value"
  select:"value"
second-fieldset (object)
  key:2
  textbox:"value"
  select:"value"

它应该在哪里:

first-fieldset (object)
  key:1
  textbox:"value"
second-fieldset (object)
  key:2
  select:"value"

我非常怀疑这是在选择字段集元素的方式,但我尝试过的所有结果都以相同的格式或根本没有数据。

4

1 回答 1

2

Seems to work fine at http://jsfiddle.net/gaby/jdR3V/1/

But it fails as you describe if you put the var fieldset = {}; outside of the .each() call.


Also, you can make a few improvements to readability and performance
(by not using $() for properties that are directly accessible, and also caching a reference to a jquery object with the fieldset element and using that to find the input elements instead of multiple dynamic selectors)

var form = {};
$('fieldset').each(function() {
  var self = $(this),
      fieldset = {};

  self.find('input:checkbox, input:radio').each(function() {
    fieldset[this.name] = this.value;
  });

  self.find('select').each(function() {
    ...
  }

  form[this.id] = fieldset;
});
于 2013-07-02T22:37:33.867 回答