【js】一些小技巧(1),将josn对象赋值给form

记录一下自己用过的方法
$.fn.setForm = function(jsonValue) {
var obj = this;
$.each(jsonValue, function(name, ival) {
var $oinput = obj.find("input[name=" + name + "]");
var $oselect = obj.find("select[name=" + name + "]")
if ($oinput.attr("type") == "radio" || $oinput.attr("type") == "checkbox") {
$oinput.each(function() {
//console.log(Object.prototype.toString.apply(ival),'++++++++++++++++')
if (Object.prototype.toString.apply(ival) == '[object Array]') { //是复选框,并且是数组

for (var i = 0; i < ival.length; i++) {
if ($(this).val() == ival[i]){ //或者文本相等


$(this).prop("checked", true);
}
}
}else {

if ($(this).val() == ival){

$(this).prop("checked", true);
}
}
});
}else if($oselect.attr("name") !== undefined){
$oselect.each(function(i) {

for (j = 0; j < $oselect[i].options.length; j++) {
if ($oselect[i].options[j].text == ival) { // 选项值与变量相同

$oselect[i].options[j].selected =true;

}
}

})

}else if ($oinput.attr("type") == "textarea") {
obj.find("[name=" + name + "]").html(ival);
} else {
obj.find("[name=" + name + "]").val(ival);
}
})
};





posted @ 2019-05-29 14:12  阳光透过幸福  阅读(664)  评论(0编辑  收藏  举报