(function ($) {
$.fn.extend({
initForm: function (options) {
//默认参数
var defaults = {
formdata: "",
isDebug: true //是否需要调试,这个用于开发阶段,发布阶段请将设置为false,默认为false,true将会把name value打印出来
}
//如果传入的json字符串,将转为json对象
var tempData = "";
if ($.type(options) === "string") {
defaults.formdata = JSON.parse(options);
} else {
defaults.formdata = options;
}
//设置参数
// var setting = $.extend({}, defaults, tempData);
var setting = defaults;
var form = this;
formdata = setting.formdata;
//如果传入的json对象为空,则不做任何操作
if (!$.isEmptyObject(formdata)) {
var debugInfo = "";
$.each(formdata, function (key, value) {
//是否开启调试,开启将会把name value打印出来
if (setting.isDebug) {
debugInfo += "name:" + key + "; value:" + value + "\r\n ";
}
//表单处理
var formField = form.find("[name=‘" + key + "‘]");
if ($.type(formField[0]) === "undefined") {
if (setting.isDebug) {
console.warn("can not find name:[" + key + "] in form!!!"); //没找到指定name的表单
}
} else {
var fieldTagName = formField[0].tagName.toLowerCase();
if (fieldTagName == "input") {
if (formField.attr("type") == "radio") {
$("input:radio[name=‘" + key + "‘][value=‘" + value + "‘]").attr("checked", "checked");
} else if (formField.attr("type") == "checkbox") {
$("input:checkbox[name=‘" + key + "‘][value=‘" + value + "‘]").attr("checked", "checked");
} else {
formField.val(value);
}
} else if (fieldTagName == "label") {
formField.html(value);
} else {
formField.val(value);
}
}
//图片链接处理form.find("img[fieldata=img_url]")
var formImage = form.find("img[fieldata=" + key + "]");
if ($.type(formImage[0]) != "undefined") {
formImage.attr("src", value);
}
//a链接处理
var formLink = form.find("a[fieldata=" + key + "]");
if ($.type(formLink[0]) != "undefined") {
formLink.attr("href", value);
}
})
if (setting.isDebug) {
console.log(debugInfo);
}
}
return form; //返回对象,提供链式操作
}
});
})(jQuery)