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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值