我正在從 API (TMDB) 獲取資料并創建一個陣列來回圈遍歷資料,我在瀏覽器的控制臺中獲得了我想要的所有內容,但是當我嘗試將它附加到DOM。謝謝
const serachbtn = document.querySelector('.search');
const input = document.querySelector('input');
const p = document.createElement('p');
document.body.appendChild(p);
let movieArray = [];
async function getmovie(){
const inputValue = input.value;
const apiUrl = `https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&query=${inputValue}`;
try{
const response = await fetch(apiUrl);
const movie = await response.json();
//const picture = "https://image.tmdb.org/t/p/w500/" movie.results[0].poster_path;
let movieArray = movie.results;
movieArray.forEach(searchie => {
console.log("title: " searchie.original_title);
console.log("Overview: " searchie.overview);
p.innerHTML = searchie.original_title;
});
}catch(error){
console.log('something went wrong');
}
}
serachbtn.addEventListener('click', (e)=>{
e.preventDefault();
getmovie();
});

uj5u.com熱心網友回復:
<p>回圈在每次迭代中替換標簽的 innerHTML,在回圈結束時只留下最后一個可見。您可以將 .html 附加到 html 中,而不是替換 =。
運行代碼段并按“搜索”按鈕查看...
const serachbtn = document.querySelector('.search');
const p = document.createElement('p');
document.body.appendChild(p);
async function pretendFetch() {
const movies = [
{ original_title: 'The Godfather' },
{ original_title: 'Star Wars' },
{ original_title: 'Jaws' },
];
return Promise.resolve(movies);
}
async function getmovie() {
try {
const movieArray = await pretendFetch();
movieArray.forEach(searchie => {
console.log("title: " searchie.original_title);
// this is the important change: append, don't replace
p.innerHTML = searchie.original_title '<br/>';
});
} catch (error) {
console.log(error);
}
}
serachbtn.addEventListener('click', (e) => {
e.preventDefault();
getmovie();
});
<button class="search">Search</button>
有許多其他方法可以添加到 DOM,包括為每個 API 結果添加一個新標簽。
為此,您將appendChild()在回圈中使用,而不是在開始時使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/459036.html
標籤:javascript api dom
