猿问

如何使用来自 API 的数据输出乘法 div

我正在使用 API,但我完全不知道如何使用来自 3 个不同对象的数据输出 3 个 div。发生的事情是 JS 只输出一个 div。我想知道如何防止JS覆盖?


  function reviews(id){

    fetch(`https://api.themoviedb.org/3/movie/${id}/reviews?api_key=9250b9e19854d9deaa571f4074bc38a3&language=en-US&page=1` ,{

        method: "GET",

    })

    .then(response => {

        return response.json();

    })

    .then(data => {

        console.log(data);

        output = '';

        for (i = 0; i <3; i++) {

            output = `

            <img src="https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png" class="align-self-start mr-3">

            <div class="media-body>

            <h5 class="mt-0 review-title">A Review by ${data.results[i].author}</h5>

            <p class="review-author">${data.results[i].author}</p>

            <p class="review-paragraph">${data.results[i].content.substring(0,200)}... <a href="#" class="see-more">see more</a></p>

            </div>

            `  

        }

        document.querySelector('.reviews-container').innerHTML = output;

    })

    .catch(showAlert())

  }


慕哥9229398
浏览 141回答 1
1回答

偶然的你

循环执行后,您将在 DOM 中输出 html 字符串。那只会输出 DOM 中的最后一个 html 字符串。您需要附加 html,而不是覆盖它并将 html 添加到循环内的 DOM使用Element.insertAdjacentHTML()函数for (i = 0; i < 3; i++) {&nbsp; &nbsp; ...&nbsp; &nbsp; document.querySelector('.reviews-container').insertAdjacentHTML("beforeend", output);&nbsp;}您也可以使用+=运算符for (i = 0; i < 3; i++) {&nbsp; ...&nbsp; document.querySelector('.reviews-container').innerHTML += output;}出于性能原因,您应该移动以下语句document.querySelector('.reviews-container')退出循环体并将其保存在某个变量中。const el = document.querySelector('.reviews-container');for (i = 0; i <3; i++) {&nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; &nbsp;el.insertAdjacentHTML("beforeend", output);&nbsp;}您还可以将 HTML 字符串与output变量连接,然后innerHTML在循环执行后设置元素的。这比DOM在循环中访问要好。&nbsp;for (i = 0; i <3; i++) {&nbsp; &nbsp; &nbsp; output += `...`&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;document.querySelector('.reviews-container').innerHTML = output;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答