我正在尝试从JSON文件构建html表。当我使用javascript中的模板文字制作表格时,它会遍历整个表格并为json中的每个数组制作一个表格标题。
我试图为我的th和td做两个函数,但这似乎不起作用。
var petsData = [{
name: "Purrsloud",
species: "Cat",
favFoods: ["wet food", "dry food", "<strong>any</strong> food"],
birthYear: 2016,
photo: "https://learnwebcode.github.io/json-example/images/cat-2.jpg"
},
{
name: "Barksalot",
species: "Dog",
birthYear: 2008,
photo: "https://learnwebcode.github.io/json-example/images/dog-1.jpg"
},
{
name: "Meowsalot",
species: "Cat",
favFoods: ["tuna", "catnip", "celery"],
birthYear: 2012,
photo: "https://learnwebcode.github.io/json-example/images/cat-1.jpg"
}
];
function foods(foods) {
return `
<h4>Favorite Foods</h4>
<ul class="foods-list">
${foods.map(food => `<li>${food}</li>`).join("")}
</ul>
`;
}
function petTemplate(pet) {
return `
<table>
<tr>
<th>Name</th>
<th>Species</th>
<th>Birth Year</th>
<th>Favorite Foods</th>
</tr>
<td>${pet.name}</td>
<td>${pet.species }</td>
<td>${pet.birthYear}</td>
<td>${pet.favFoods ? foods(pet.favFoods) : ""}</td>
<tr>
</tr>
</table>
`;
}
document.getElementById("table").innerHTML = `
${petsData.map(petTemplate).join("")}
`;
<div id="table"></div>
似乎我的petTable函数不断循环,直到我获得json文件中的所有数组为止,但这为每个json数组的每个数组创建了一个表头。我只想要一个表头,然后是所有数组。
答案 0 :(得分:2)
“但是似乎不起作用”有点含糊,但是当然,如果将标题单元格与行保持在同一位置,它们将显示在每行上方。您可以简单地将开始和结束标记放入变量中,并使用行生成功能在实际循环数据之前和之后输出这些变量。
您的原始标记中还有一个错误,第二个开头<tr>
恰好在其结束副本之前,而不是相应的<td>
标签之前。
var petsData = [{
name: "Purrsloud",
species: "Cat",
favFoods: ["wet food", "dry food", "<strong>any</strong> food"],
birthYear: 2016,
photo: "https://learnwebcode.github.io/json-example/images/cat-2.jpg"
},
{
name: "Barksalot",
species: "Dog",
birthYear: 2008,
photo: "https://learnwebcode.github.io/json-example/images/dog-1.jpg"
},
{
name: "Meowsalot",
species: "Cat",
favFoods: ["tuna", "catnip", "celery"],
birthYear: 2012,
photo: "https://learnwebcode.github.io/json-example/images/cat-1.jpg"
}
];
var tableStart = `
<table>
<tr>
<th>Name</th>
<th>Species</th>
<th>Birth Year</th>
<th>Favorite Foods</th>
</tr>`;
var tableEnd = `
</table>`;
function foods(foods) {
return `
<h4>Favorite Foods</h4>
<ul class="foods-list">
${foods.map(food => `<li>${food}</li>`).join("")}
</ul>
`;
}
function petTemplate(pet) {
return `
<tr>
<td>${pet.name}</td>
<td>${pet.species }</td>
<td>${pet.birthYear}</td>
<td>${pet.favFoods ? foods(pet.favFoods) : ""}</td>
</tr>
`;
}
document.getElementById("table").innerHTML = `
${tableStart}
${petsData.map(petTemplate).join("")}
${tableEnd}
`;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table"></div>
答案 1 :(得分:0)
如果在底部看到您正在使用地图数据集,并将petTemplate作为回调函数传递。导致重复执行。
您必须从petTemplate中删除表和逻辑,因为这应该调用数据中的每个元素