日期:2014-05-16  浏览次数:20389 次

js生成Table最好的例子并且获取table json,Copy即可运行
<html>
<head>
</head>
<script>
function addRow(){
	
	var testTable = document.getElementById("testTable");
	var rows = testTable.getElementsByTagName("tr").length;
	var newRow = testTable.insertRow(rows);
	var cell1 = newRow.insertCell(0);
	cell1.innerHTML="<input id='name"+rows+"' type='text' value='computer"+rows+"'>";
	var cell2 = newRow.insertCell(1);
	cell2.innerHTML="<input id='price"+rows+"' type='text' value='price"+rows+"'>"

}

/**
 *  打印数据
 *
 */
function printData(){
	//获取数据
	var data = addData();
	//转换成对象
	var dataVar = eval('('+data+')');

	for(var j=0; j<dataVar.length ; j++){
		var values= dataVar[j];
		alert("name:"+values.name+"\n"+"price:"+values.price);
	}
}
/**
 *  装载数据
 *
 */
function addData(){
	//数据集合
	var datas="[";
	var trs = testTable.getElementsByTagName("TR");

	var rows = testTable.getElementsByTagName("TR").length;
	//因为有表头所以从第二行开始是数据
	for(var i = 1; i < rows ; i++){
		//一对数据
		var data ="";
		var tr = trs[i];
		if(i==1){
			data += "{";
		}else{
			data += ",{";
		}
		var name = tr.firstChild.firstChild.value;
		var price = tr.lastChild.firstChild.value;
		data += "name:'"+name+"',price:'"+price+"'}";
		datas +=data;
	}
	datas += "]";
	//alert(datas);
	return datas;
}
</script>
<body>
<form>
	<table id="testTable">
		<tr>
			<th>笔记本</th>
			<th>价格</th>
		</tr>
		<tr>
			<td>
				<input id="name0" type="text" value='compute1'>
			</td>
			<td>

				<input id="price0" type="text"  value='price1'>
			</td>
		</tr>
		<tr>
			<td>
				<input id="name1" type="text"  value='compute2'>
			</td>
			<td>

				<input id="price1" type="text"  value='price2'>
			</td>
		</tr>
		<tr>
			<td>
				<input id="name2" type="text" value='compute3'>
			</td>
			<td>

				<input id="price2" type="text"  value='price3'>
			</td>
		</tr>
	<table>

	<input id="1" type="button" value="增加一行" onclick="addRow()"/>
	<input id="2" type="button" value="打印数据" onclick="printData()"/>
</form>
</body>
</html>