将提取数据添加到DOM

问题描述 投票:0回答:2

我正在尝试从API中提取7种产品,并在DOM中显示它们。当我尝试为每个产品创建一个div并将其插入HTML时,我得到一个div,其中包含“ 、、、、、、、”。由于我能够从API控制台记录数据,因此该请求正在运行。

const results = document.getElementById('result');
      
fetch('http://localhost:1337/products')
.then(response => response.json())
.then((data) =>{
results.innerHTML = data.map(product =>{ 
  console.log(product.meal);
    `
  <div class="result">
    <h3>${product.meal}</h3>
    <p>${product.description}</p>
    <p>${product.price}</p>
  </div>
    `
  })
 
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Med Kitchen Prep</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro&display=swap" rel="stylesheet">
</head>
<body>
    

<section id="a">
   
        <nav id="main-nav">
            <a id="logopic" href="/"><img src="./img/logo.png" alt="logo image"></a>
          <ul>
            <li><a href="index" class="current">Home</a></li>
            <li><a href="#">Meals</a></li>
          </ul>
        </nav>
        <div class="header-content">
          <h1>
            Mediterranean Kitchen Prep
          </h1>
          <p class="lead">
            Mediterranean Meals Delivered To Your Doorstep
          </p>
          <ul>
          <li><a id="view-meals" href="#">View Our Meals</a></li>
        </ul>
        </div>
     
</section>

<section id="b">
  <h2>All Meals</h2>
  <div id="result" class="result"></div>
</section>

    <script src="app.js"></script>
</body>
</html>
javascript html arrays dom innerhtml
2个回答
0
投票

尝试使用forEach

data.forEach(product => {
  console.log(product.meal);
  results.innerHTML += `
  <div class="result">
    <h3>${product.meal}</h3>
    <p>${product.description}</p>
    <p>${product.price}</p>
  </div>`
})

0
投票

您需要return功能内的值。 map将返回具有修改后值的新数组。

map
© www.soinside.com 2019 - 2024. All rights reserved.