/* * 向元素赋值(元素id要与对象属性名相同) * selector : "#table span" * jsonData: {"key":"value"} * specialData: {"propertyName":{"key":"value"}} * prefix: id是否有前缀 */ function set(selector, jsonData, specialData, prefix) { $.each($(selector), function (i, v) { var id = $(this).attr("id"); if (prefix != "") { // 去掉前缀,使id与对象属性名保持一致 id = id.replace(prefix, ""); } var eleText = jsonData[id]; if (id != "" && eleText != "") { var setByTag = function (element, value) { switch (element.tagName) { case "INPUT": switch ($(element).attr("type")) { case "text": case "hidden": $(element).val(value); break; case "checkbox": $(element).attr("checked", "checked"); break; default: break; } break; default: $(element).text(value); break; } } var elementObj = this; setByTag(this, eleText); $.each(specialData, function (i2, v2) { if (specialData[eleText] != "") { setByTag(elementObj, this[eleText]); } }); } }); }
使用示例:
<table id="tableid">
<tr>
<td class="ContentNameRequired">性别
</td>
<td class="ContentValue">
<span id="tableid_Gender"></span>
</td>
</table>
var gender = { "0": "未知", "1": "男", "2": "女" }; var stuSource = { "1": "在线报名", "2": "录入", "3": "在线邀请" }; Set("#dlg span,input", json, { "Gender": gender, "StuSource": stuSource },"tableid_");
使用标签的自定义属性也许会更好些,这样就避免了将一个对象属性赋值给多个标签时的问题 。