1.defaultValue为JavaScript DOM对象,不能直接在Jquery对象中使用,必须先转化为DOM对象;
2.defaultValue对于input type="text/hidden" 为标签上的value值,并非原始值,如果通过JS修改了value值,则对象的defaultValue也会改变;
案例分析:想实现修改表单,提交的时候只需提交修改的字段
function submitForm(){
var elements = document.getElementById("commentForm");
var len = elements.length;
var updateBool = false;
var jsonObj = {};
for(var i=0;i<len;i++){
var field = elements[i];
if((field.type=="text" || field.type=="textarea" || field.type=="file" || field.type=="hidden" || field.type=="select-one") ){
if(field.name=="id"){
jsonObj = {};
jsonObj[field.name] = field.value;
}else if(field.name!=""&&isdirty(field)){
jsonObj[field.name] = field.value;
updateBool = true;
}
}
}
//如果数组数据为空,则不提交数据
if(!updateBool){
layer.msg('暂无修改数据', function(){
//关闭后的操作
});
return false;
}
//ajax保存数据
$.ajax({
type:"post",
url:"",
dataType:"json",
contentType:"application/json;charset=utf-8",
data:JSON.stringify(jsonObj), //这个方法是将json的字符串形式转换成json对象,后台接收到的时候是一个整体的对象,而不是字符串。
beforeSend:function(){
layer.load(2);
},
success: function(data) {
},
error:function(e){
}
});
}
function isdirty(control){
return (getControlValue(control) != getControlDefaultValue(control));
}
function getControlValue(control){
if(control.type == 'checkbox'){
return control.checked;
} else if(control.type == 'radio'){
return control.checked;
} else if(control.type == 'select-one'){
for(var i=0; i<control.options.length; i++){
if(control.options[i].selected)
return control.options[i].value;
}
return null;
} else
return control.value;
}
function getControlDefaultValue(control){
if(control.type == 'checkbox'){
return control.defaultChecked;
} else if(control.type == 'radio'){
return control.defaultChecked;
} else if(control.type == 'select-multiple'){
return null;
} else if(control.type == 'select-one'){
for(var i=0; i<control.options.length; i++){
if (control.options[i].defaultSelected)
return control.options[i].value;
}
if(control.options.length > 0) return control.options[0].value;
return null;
} else
return control.defaultValue;
}