你可以这样做:
var fields = {};
$("#theForm").find(":input").each(function() {
// The selector will match buttons; if you want to filter
// them out, check `this.tagName` and `this.type`; see
// below
fields[this.name] = $(this).val();
});
var obj = {fields: fields}; // You said you wanted an object with a `fields` property, so...
请注意,表单可能包含重复名称的字段,而您尝试执行的操作不支持该字段。此外,HTML 表单中的字段顺序也很重要。(这些都是以serializeArray
它的方式运作的原因。)
请注意,正常的 HTML 做法是省略禁用的字段。如果您想这样做,请this.disabled
在获取值之前进行检查。
请注意,上面(两年前写的)使用了一个 jQuery 伪选择器。我有点惊讶地发现我写了那个。正如它在pseudo-selector的文档中:input
所说的那样,使用它意味着 jQuery 不能将选择器交给浏览器的本机querySelectorAll
(现在几乎所有浏览器都有)。
现在我可能会写:
$("#theForm").find("input, textarea, select, button")...
...如果我想要按钮,或者如果不是那么
$("#theForm").find("input, textarea, select")...
...然后过滤掉input[type="button"]
并input[type="submit"]
在each
. 例如(根本没有按钮):
$("#theForm").find("input, textarea, select").each(function() {
var inputType = this.tagName.toUpperCase() === "INPUT" && this.type.toUpperCase();
if (inputType !== "BUTTON" && inputType !== "SUBMIT") {
// ...include it, either it's an `input` with a different `type`
// or it's a `textarea` or a `select`...
}
});