我想创建静态/动态表。行的所有单元格<th>
和前两列<td>
都是静态的。使用jQuery脚本动态创建我想要动态创建的其他单元格。
我不知道我是怎么开始的。数据到单元格我已经以JSON格式(数组)保存为:
{
"EX1":[["1","8","16","24"]],
"EX2":[["0","100200","109f","ffffffff"]]
}
HTML:
<table id="personDataTable" style="border: 1px #e3ffg3 solid; text-align: center;">
<tr class="bg02">
<th colspan="2">Name</th>
<th width="100px">Sensor 1</th>
<th width="100px">Sensor 2</th>
<th width="100px">Sensor 3</th>
<th width="100px">Sensor 4</th>
</tr>
<tr id="row1">
<td class="bg02">A</td>
<td class="bg02">Out64H</td>
<td>element[index]</td>
<td>element[index+1]</td>
<td>element[index+2]</td>
<td>element[index+3]</td>
</tr>
<tr id="row2">
<td class="bg02">R</td>
<td class="bg02">In128Birh</td>
<td>element[index]</td>
<td>element[index+1]</td>
<td>element[index+2]</td>
<td>element[index+3]</td>
</tr>
</table>
每个<tr>
中的静态文本都是必需的,因为文本不在json文件中。
可以通过创建javascript脚本寻求帮助吗?
非常感谢
答案 0 :(得分:1)
请参阅此jsfiddle:http://jsfiddle.net/9zr6z70g/3/
jQuery代码是这样的:
var data = {
"EX1":[["1","8","16","24"]],
"EX2":[["0","100200","109f","ffffffff"]]
};
var data1 = data.EX1[0];
var data2 = data.EX2[0];
$(document).ready(function(){
var row1cells = $("#row1 td");
var row2cells = $("#row2 td");
for (var index=0; index<4; index++) {
$(row1cells[index+2]).html(data1[index]);
$(row2cells[index+2]).html(data2[index]);
}
});
对于多个EX数据,请按以下方式执行操作:
var exCount = 2;
var data = {
"EX1":[["1","8","16","24"]],
"EX2":[["0","100200","109f","ffffffff"]]
};
$(document).ready(function(){
for (var index=1; index<=exCount; index++) {
var cells = $("#row"+index+" td");
var values = data["EX"+index][0];
for (var jndex=0; jndex<4; jndex++) {
$(cells[jndex+2]).html(values[jndex]);
$(cells[jndex+2]).html(values[jndex]);
}
}
});
多个EX的更多详细信息,请参阅jsfiddle:http://jsfiddle.net/9zr6z70g/7/
答案 1 :(得分:0)
此代码适合我,但变量 EX 超过一百。
var data = {
"EX1":[["1","8","16","24"]],
"EX2":[["0","100200","109f","ffffffff"]]
};
var data1 = data.EX1[0];
var data2 = data.EX2[0];
$(document).ready(function(){
var row1cells = $("#row1 td");
var row2cells = $("#row2 td");
for (var index=0; index<4; index++) {
$(row1cells[index+2]).html(data1[index]);
$(row2cells[index+2]).html(data2[index]);
}
});
我尝试使用 for loop 修改代码。此解决方案无法正常工作。
var data = {
"EX1":[["1","8","16","24"]],
"EX2":[["0","100200","109f","ffffffff"]]
};
var data1 = data.EX1[0];
var data2 = data.EX2[0];
$(document).ready(function(){
for (j=1; j<4; j++) {
var pom = "row"+[j]+"cells";
var pom2 = "#row"+[j]+" td";
var pom3 = "$"+'("'+pom2+'")';
for (var index=0; index<4; index++) {
$(pom3+[index+2]).html(data[j][index]);
}
}
});
可以请求修改帮助吗?感谢