小编Lou*_*uis的帖子

javascript中的模板文字循环

我正在尝试用 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> …
Run Code Online (Sandbox Code Playgroud)

html javascript

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

html ×1

javascript ×1