这是第一个功能:
jQuery.fn.serializeObject = function(){
var self = this,
json = {},
push_counters = {},
patterns = {
"validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
"key": /[a-zA-Z0-9_]+|(?=\[\])/g,
"push": /^$/,
"fixed": /^\d+$/,
"named": /^[a-zA-Z0-9_]+$/
};
this.build = function(base, key, value){
base[key] = value;
return base;
};
this.push_counter = function(key){
if(push_counters[key] === undefined){
push_counters[key] = 0;
}
return push_counters[key]++;
};
jQuery.each(jQuery(this).serializeArray(), function(){
// skip invalid keys
if(!patterns.validate.test(this.name)){
return;
}
var k,
keys = this.name.match(patterns.key),
merge = this.value,
reverse_key = this.name;
while((k = keys.pop()) !== undefined){
// adjust reverse_key
reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');
// push
if(k.match(patterns.push)){
merge = self.build([], self.push_counter(reverse_key), merge);
}
// fixed
else if(k.match(patterns.fixed)){
merge = self.build([], k, merge);
}
// named
else if(k.match(patterns.named)){
merge = self.build({}, k, merge);
}
}
json = jQuery.extend(true, json, merge);
});
return json;
};
这个函数可以序列化表单的值,但是这个函数的问题是它没有得到未经检查的输入的值,因为我创建了这个函数:
jQuery.fn.mySerialize = function() {
var $container = jQuery(this),
$checkboxes = $container.find("input[type='checkbox']").each(function() {
jQuery(this).val(this.checked ? 1 : 0).prop('checked', true);
});
var serialized = ($container.serializeObject());
$checkboxes.each(function() {
jQuery(this).prop('checked', jQuery(this).val() == 1);
});
return serialized;
};
现在直接使用mySerialize
函数正常工作我想将mySerialize
函数的编辑合并到serializeObject
函数,因为我没有直接这样做进入serializeObject
函数,因为我创建了mySerialize
函数。
提前致谢,真的希望有人帮助我。