你可以這樣做:
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僞選擇器。我有點驚訝地發現我寫了這個。正如它在documentation for the :input
pseudo-selector中所述,使用它意味着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`...
}
});
有什麼使命?你打算如何處理這個對象? – Canuteson 2011-04-09 05:42:49
我想創建一個驗證表單的ajax腳本。和一些領域取決於其他領域,所以我只是發送整個對象上的任何輸入更改... – Alex 2011-04-09 05:46:16