Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery.fn.each创建JSON对象_Jquery_Json_Each - Fatal编程技术网

jQuery.fn.each创建JSON对象

jQuery.fn.each创建JSON对象,jquery,json,each,Jquery,Json,Each,下面使用jQuery.fn.each构建一个包含JSON对象的变量。问题是添加到数组会导致JavaScript错误 var formfields = { step: $(this).data('step') } $(this).parent().parent().parent().find('input').each(function(){ formfield += $(this).attr('name'):$(this).val(); // This line is the prob

下面使用
jQuery.fn.each
构建一个包含JSON对象的变量。问题是添加到数组会导致JavaScript错误

var formfields = { step: $(this).data('step') }

$(this).parent().parent().parent().find('input').each(function(){
    formfield += $(this).attr('name'):$(this).val(); // This line is the problem
});

alert(form fields);
如何做到这一点。

您需要使用

  • 多次使用而不是调用.parent()
  • 您还可以使用
    this.name
    来访问输入的名称,而不是使用
    $(this.attr('name')
试试这个

var formfields = {step: $(this).data('step')};

$(this).parent().parent().parent().find('input').each(function () {
    formfields[$(this).prop('name')] = $(this).val();
});

console.log(formfields);

下面是使用
serializeArray()
的另一种方法:


第3行仍然需要一个分号。此外,第五行添加到不存在的
formfield
。结尾的
警报
也需要注意:
表单字段
不是有效的变量名。您真的需要对象还是只是试图将数据传递给ajax调用?
var formfields = {step: $(this).data('step')};

$(this).parent().parent().parent().find('input').each(function () {
    formfields[$(this).prop('name')] = $(this).val();
});

console.log(formfields);
var formfields = { step: $(this).data('step') };

var formfieldsarray = $(this).parent().parent().parent().find('input').serializeArray();

$.each(formfieldsarray, function() {
    formfields[this.name] = this.value;
});