gpt4 book ai didi

javascript - javascript中的模板文字循环

转载 作者:行者123 更新时间:2023-11-27 22:55:49 24 4
gpt4 key购买 nike

我正在尝试从 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 数组创建了一个表头。我只想要一个表头,然后是所有数组。

最佳答案

“但这似乎不起作用”有点含糊,但当然,如果您将标题单元格与行放在同一位置,它们将显示在每一行上方。您可以简单地将开始和结束标记放入变量中,并在使用行生成函数实际循环数据之前和之后输出它们。

您的原始标记中也存在错误,第二个开口为 <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>

关于javascript - javascript中的模板文字循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55976205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com