未压缩版
jQuery.fn.extend({
serialize:function() {
return jQuery.param(this.serializeArray());
},
serializeArray:function() {
var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i;
var rcheckableType = /^(?:checkbox|radio)$/i;
var rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]+)/i;
var rscriptType = /^$|\/(?:java|ecma)script/i;
return this.map(function() {
var elements = jQuery.prop(this, "elements");
return elements ? jQuery.makeArray(elements) :this;
}).filter(function() {
var type = this.type;
return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type));
}).map(function(i, elem) {
var val = jQuery(this).val();
if (val == null) {
return null;
}
if (val == "") {
if (jQuery(this).is("[default]")) {
val = jQuery(this).attr("default");
}
}
if (Array.isArray(val)) {
return jQuery.map(val, function(val) {
return {
name:elem.name,
value:val.replace(rCRLF, "\r\n")
};
});
}
return {
name:elem.name,
value:val.replace(rCRLF, "\r\n")
};
}).get();
}
});
压缩版
jQuery.fn.extend({ serialize: function () { return jQuery.param(this.serializeArray()) }, serializeArray: function () { var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; var rcheckableType = (/^(?:checkbox|radio)$/i); var rtagName = (/<([a-z][^\/\0>\x20\t\r\n\f]+)/i); var rscriptType = (/^$|\/(?:java|ecma)script/i); return this.map(function () { var elements = jQuery.prop(this, "elements"); return elements ? jQuery.makeArray(elements) : this }).filter(function () { var type = this.type; return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type)) }).map(function (i, elem) { var val = jQuery(this).val(); if (val == null) { return null } if (val == "") { if (jQuery(this).is("[default]")) { val = jQuery(this).attr("default") } } if (Array.isArray(val)) { return jQuery.map(val, function (val) { return { name: elem.name, value: val.replace(rCRLF, "\r\n") } }) } return { name: elem.name, value: val.replace(rCRLF, "\r\n") } }).get() } });
文本框的添加属性 default
<form id="from">
<input type="input" name="name" default="test"/>
</form>
使用方法
$("#form").serialize();