/*jquery 扩展方法 */
!function($){
//form表单格式化
$.fn.extend({
formToJson: function(){
var json = {};
this.serializeArray().forEach(function(item){
json[item.name] = item.value;
});
return json;
},
assignment: function(obj){
var key;
for(key in obj){
if(key.toLowerCase() == "avatar_url"){
$(this).find("#"+ key).attr("src", BaseConfig.Const.DOWN_HOST + BaseConfig.Const.UPLOAD_FILE_PATH + obj[key]);
}else{
$(this).find("#"+ key).html(obj[key]);
}
}
},
formAssignment: function(){
var FormUtil={
//设置文本框 文本域 密码框 隐藏框
setValue:function(key,value){
$("#"+key).val(value);
},
//设置下拉框
setSelect:function(key,value){
$("#"+key+" option").each(function(){
if(this.value==value){
$(this).attr("selected","selected");
}
});
},
//设置radio
setRadio:function(key,value){
// $(":radio[name='"+key+"']").removeAttr("checked");
$(":radio[value='"+value+"']").attr("checked","checked");
},
//设置checkbox
setCheckbox:function(key,value,isDefault){
$(":checkbox[name='"+key+"']").attr("checked",false);
if(isDefault){
var vs=value.split("");
for(var i=vs.length-1;i>=0;i--){
if(vs[i]=="1"){
$(":checkbox[name='"+key+"']").filter(":eq("+(vs.length-1-i)+")").attr("checked",true);
}
}
}else {
}
},
//input类型判断
judgeType:function(type,key,value){
if(type=="text"||type=="password"||type=="hidden"){
FormUtil.setValue(key,value);
}else if(type=="radio"){
FormUtil.setRadio(key,value);
}else if(type=="checkbox"){
FormUtil.setCheckbox(key,value,true);
}
}
}
return function (obj){
var attr;
for(attr in obj){
var element=$("#"+attr);
if(!element[0]) continue;
var nodeName=element[0].nodeName;
if(nodeName=="INPUT"){
FormUtil.judgeType($(element).attr("type"),attr,obj[attr]);
}else if(nodeName=="SELECT"){
FormUtil.setSelect(attr,obj[attr]);
}else if(nodeName=="TEXTAREA"){
FormUtil.setValue(attr,obj[attr]);
}else{
element.html(obj[attr])
}
}
}
}()
})
}(jQuery)
例子:
var params = $("#infoForm").formToJson();
html:
<div class="L-The-briefing" id="abc">
<h1 id="title"></h1>
<span id="person_name"></span>
</div>
js:
$("#abc").assignment(data.list);
html:
<form id="infoForm" class="L-Personal-center">
<div class="fl L-Personal-left ">
<img id="logoUrl" src="../../../images/student/L-Personal-center-img.jpg" width="193" height="238"/>
<input type="hidden" name="AVATAR_URL" id="AVATAR_URL" value="">
<button type="button" class="L-Personal-left-button" onclick="ModifyBaseInfo.uploadLogo()">上传头像</button>
</div>
<div class="fl L-Personal-right ">
<dl class="L-Personal-dl">
<dt>账号:</dt>
<dd><input type="text" class="ipt-norWidthIpt" name="LOGIN_NAME" readonly id="login_name"></dd>
</dl>
<dl class="L-Personal-dl">
<dt>姓名:</dt>
<dd>
<input type="text" class="ipt-norWidthIpt" name="PERSON_NAME" value="" id="person_name">
</dd>
</dl>
</form>
js:
$("#infoForm").formAssignment(res);