文章说明:
本文介绍了根据Json串生成Html的一种方式(只是简单实现了文本框,密码框,下拉框)。只是觉得好玩才这样做,如果觉得没有任何价值,请忽略。不足指出希望各位大牛指点。后续将根据各位的指点继续完善。

功能说明:
根据json字符串生成Html的一种方式
在左侧输入框中输入Json串,点击执行时根据输入的Json串在右侧展示区显示出相应的Html(使用Jquery1.4.4)
HTML:

代码如下:

<table style="width:100%; "> 
<col width="200px;" /> 
<tr> 
<td>Json输入框</td> 
<td>展示区</td> 
</tr> 
<tr> 
<td> 
<textarea id="txtJson" rows="20" cols="50"> 
</textarea> 
</td> 
<td valign="top"> 
<div id="divShow"> 
</div> 
</td> 
</tr> 
<tr> 
<td></td> 
<td> 
<input id="btnExec" type="button" value="执行" /> 
</td> 
</tr> 
</table>

JS代码:

代码如下:

$(document).ready(function () { 
  $("#btnExec").click(function () { 
try{ 
var objList = eval($("#txtJson").val()); 
jsonToControl(objList); 
} 
catch(e){ 
alert("json格式错误"); 
} 
}); 
}); 
function jsonToControl(jsonObj) { 
$("#divShow").empty(); 
$.each(jsonObj, function (index, item) { 
var control = null; 
var title = $("<label />"); 
switch (item.type) { 
case "textbox": 
control = createTextBox(); 
break; 
case "select": 
control = createSelect(item); 
break; 
case "password": 
control = createPassword(); 
break; 
//------------------------------ 
// 其它控件在这里加代码 
//------------------------------ 
} 
if (item.title != null) { 
title.text(item.title); 
} 
if (control != null) { 
control = setAttritube(control, item); 
$("#divShow").append(title); 
$("#divShow").append(control); 
$("#divShow").append("<br/>"); 
} 
}) 
} 
//设置控件的样式 
function setAttritube(control, item) { 
if (item.width != null) { 
control.width(item.width); 
} 
//-------------------------------- 
// 其他样式在这里加代码 
//-------------------------------- 
return control; 
} 
//创建TextBox 
function createTextBox() { 
return $("<input type='textbox' />"); 
} 
//创建密码框 
function createPassword() { 
return $("<input type='password'/>"); 
} 
//创建Select 
function createSelect(item) { 
var c = $("<select></select>"); 
if(item.items != null ){ 
$.each(item.items,function(index,i){ 
$("<option value='"+i.key+"' checked='checked'>"+i.value+"</option>").appendTo(c); 
}) 
} 
return c; 
}

非常感谢各位抽空看完。如果有任何意见或建议,请留言。