我在这段代码中无法弄清楚这个问题。 它应该迭代数组对象并将它们显示在HTML表中。第三行应包含按钮。为什么它没有给我看任何东西?
HTML code:
<html>
<head>
</head>
<body>
<div id="wrapper">
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<tr>
<th>Name</th>
<th>Level</th>
<th>Action</th>
</tr>
<tr id="table-rows">
<td><input type="text" id="new_name"></td>
<td>
<select name="levels-list" id="levels-list">
<option value="A" id="option-1">A</option>
<option value="B" id="option-2">B</option>
<option value="C" id="option-3">C</option>
</select>
</td>
<td><input type="button" class="add" value="Add Row" id="add-button"></td>
</tr>
</table>
</div>
<script type="text/javascript" src="myscript.js"></script>
</body>
</html>
使用Javascript:
var myArray = [{"name":"aaa","level":"A"},{"name":"bbb","level":"B"},{"name":"ccc","level":"C"}];
display();
function display() {
var length = myArray.length;
var htmltext = "";
for (var i = 1; i < length; i++) {
htmltext +=
"<tr id='row"+i+"'>\
<td>"+myArray[i].name+"</td>\
<td>"+myArray[i].level+"</td>\
<td>\
<input type='button' id='edit_button"+i+"' value='Edit' class='edit' onclick='edit_row("+i+")'> \
<input type='button' id='save_button"+i+"' value='Save' class='save' onclick='save_row("+i+")'> \
<input type='button' value='Delete' class='delete' onclick='delete_row("+i+")'>\
</td>\
</tr>";
}
document.getElementById("table-rows").innerHTML = htmltext;
}
答案 0 :(得分:0)
而不是
document.getElementById("table-rows").innerHTML = htmltext;
尝试
document.getElementById("table-rows").append(htmltext);
答案 1 :(得分:0)
您需要使用ID引用表体,并且,for循环应该初始化为0,因此您可以遍历整个数组。
var myArray = [{
"name": "aaa",
"level": "A"
}, {
"name": "bbb",
"level": "B"
}, {
"name": "ccc",
"level": "C"
}];
display();
function display() {
var length = myArray.length;
var htmltext = "";
for (var i = 0; i < length; i++) {
htmltext +=
"<tr id='row" + i + "'>\
<td>" + myArray[i].name + "</td>\
<td>" + myArray[i].level + "</td>\
<td>\
<input type='button' id='edit_button" + i + "' value='Edit' class='edit' onclick='edit_row(" + i + ")'> \
<input type='button' id='save_button" + i + "' value='Save' class='save' onclick='save_row(" + i + ")'> \
<input type='button' value='Delete' class='delete' onclick='delete_row(" + i + ")'>\
</td>\
</tr>";
}
document.getElementById("table-rows").innerHTML = htmltext;
}
<html>
<head>
</head>
<body>
<div id="wrapper">
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<thead>
<tr>
<th>Name</th>
<th>Level</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table-rows">
<tr>
<td><input type="text" id="new_name"></td>
<td>
<select name="levels-list" id="levels-list">
<option value="A" id="option-1">A</option>
<option value="B" id="option-2">B</option>
<option value="C" id="option-3">C</option>
</select>
</td>
<td><input type="button" class="add" value="Add Row" id="add-button"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
答案 2 :(得分:-2)
使用把手。 http://handlebarsjs.com/ 我自己用它来做动态表。加上用js插入html的不良做法。