javascript - 使用 for 循环将列表数组插入 html 页表
问题描述
我正在构建一个网站页面,其中将显示一个表格以显示餐厅的排名、名称、地址和电话号码。首先,我正在尝试编写一个 for 循环,它将示例数组列表插入到表中。表格的标题和样式工作正常,但不知何故我无法将数组列表插入表格主体。代码如下:
<!DOCTYPE html>
<html>
<head>
<link href="static/css/style2.css" type="text/css" rel="stylesheet">
<title>The Top Ten Restaurants in {{zip_code}}</title>
</head>
<body>
`<h1>Yelp Rating System</h1>`
<h2>Top 10 restaurants in zip code: {{zip_code}}</h2>
<table id="table" class="table">
<thead>
<tr>
<th>Rank</th>
<th>Restaurant Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<!-- <tr>
<td><a href="{{ url_for('restaurant', restaurant_info=11355 )}}"> Restaurant x</a></td>
</tr>
-->
</tbody>
</table>
<script>
var array =
[
["1","Kiku", "555 5th ave, New York, NY 11355", "212-111-2222"],
["2","Yamoto", "444 6th ave, New York, NY 11355", "212-888-9999"]
],
var table = document.getElementById("table");
for(var i = 0; i <table.rows.length; i++)
{
for(var j = 0; j< table.rows[i].cells.length; j++)
{
table.rows[i].cells[j].innerHTML = array[i - 1][j];
}
}
/*for (var i = 0; i < array.length; i++)
{
var newRow = table.insertRow(table.length);
for (var j = 0; j< array[i].length; j++)
{
var cell = newRow.insertCell[j];
cell.innerHTML = array[i]][j];
}
}*/
</script>
</body>
</html>
我还想问一下数据是否成功插入到表中,如何将表的第 1 列变成另一个 HTML 脚本的超链接。
解决方案
如果我的问题正确,请尝试此代码。
<!DOCTYPE html>
<html>
<head>
<link href="static/css/style2.css" type="text/css" rel="stylesheet">
<title>The Top Ten Restaurants in {{zip_code}}</title>
</head>
<body>
<h1>Yelp Rating System</h1>
<h2>Top 10 restaurants in zip code: {{zip_code}}</h2>
<table id="table" class="table">
<thead>
<tr>
<th>Rank</th>
<th>Restaurant Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody id = "records">
<!-- record will be inserted here -->
</tbody>
</table>
</body>
</html>
<script>
var array = [
["1","Kiku", "555 5th ave, New York, NY 11355", "212-111-2222"],
["2","Yamoto", "444 6th ave, New York, NY 11355", "212-888-9999"]
];
var table = document.getElementById("table");
// console.log(array.length);
var data = "";
for(var i = 0; i < array.length; i++){
data += "<tr>";
for(var j = 0; j < array[i].length; j++){
if(j == 0){
data += "<td><a href = '#'>" + array[i][j] + "</a></td>";
}else{
data += "<td>" + array[i][j] + "</td>";
}
}
data += "</tr>";
}
var tbody = document.getElementById("records");
tbody.innerHTML = data;
</script>