本文介绍了jQuery $('form')。serialize()只返回序列化表单的一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下表格:

<form id="form" name="form">
<input name="name"/>
<input name="version"/>
<input name="template"/>
<textarea name="elements"></textarea>
<textarea name="features"></textarea>
<textarea name="layout"></textarea>
<input type="submit" value="Save"/>
</form>

和javascript(使用jQuery 1.3.2):

and javascript (using jQuery 1.3.2):

$(function() {
    $('#form').bind('submit',function() { alert($('#form').serialize()); return false; });
    });

从上面的javascript警告提交上述表单的输出是:

The output of submitting the above form from the above javascript alert is:

elements=...

where ...是元素字段中包含的内容。

Where ... is whatever is contained in the elements field.

我希望$('#form')。serialize()返回类似字符串的内容:

I would expect that $('#form').serialize() to return a string something like:

name=&version=&template=&elements=&features=&layout=.

我注意到$('input,textarea')。serialize()执行预期的行为(即返回name =& version =& template =& elements = asdafe& features =& layout =),但我很好奇$('#form) ')版本只返回elements =。

I do note that $('input,textarea').serialize() does perform the expected behaviour (i.e. return "name=&version=&template=&elements=asdafe&features=&layout="), however I'm curious as to why the $('#form') version only returns "elements=".

我在Safari 4和Firefox 3.5上试过这个,所以我很有信心这是我所缺少的。

I've tried this on Safari 4 and Firefox 3.5, so I'm confident it's something I'm missing.

感谢您阅读。

推荐答案

这是您的textarea的名称抛弃它。

It's the name of your textarea that's throwing it off.

以下是它如何分解。在DOM中,表单节点有几个特殊属性,最明显的是这两个(按此顺序公开)

Here's how it breaks down. In the DOM, form nodes have several special properties, most notably these two (which are exposed in this order)


  1. 元素集合,这是所有表单控件(以及一些其他节点,如< fieldset> elements)

  2. 表单中每个命名元素的属性(即具有 name 属性的表单控件)

  1. The elements collections, which is an HTMLCollection of all the form controls (and a few other nodes like <fieldset> elements)
  2. A property of each named element in the form (i.e., form controls that have a name attribute)

因为你有一个名为elements的< textarea> ,这有效地覆盖了上面#1中提到的内置元素集合,这就是为什么当你序列化表单时,你看到的只是

Since you have a <textarea> with the name "elements", this effectively overwrites the built-in elements collection mentioned in #1 above, which is why when you serialize the form all you see is

elements=****

因为单个表单元素已覆盖整个集合。

Because that single form element has overwritten the entire collection.

简短解决方案?将表单元素重命名为不是现有DOM属性的值(您的< input name =name/> 也属于此类别)

Short solution? re-name your form elements to values that aren't existing DOM properties (your <input name="name"/> falls into this category as well)

这篇关于jQuery $('form')。serialize()只返回序列化表单的一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 08:59