我正在使用OMDB API。但我在获取ID时遇到问题。我创建了一个movieID的全局变量,然后从第一个函数中的API中给它提供了电影ID,当我试图在其他函数中获取这些ID时,我只得到了我得到的MOVIES列表的最后一个ID,它是No。 10。
const url = 'http://www.omdbapi.com/?s=';
const apiId = '&ap6465465454';
const input = document.querySelector('input');
const movieDtl = document.querySelector('.movie-detail');
const ul = document.querySelector('ul');
const xhr = new XMLHttpRequest();
var movieId = null;
let inputsearch;
let object;
let movieList;
let movieDetail;
input.addEventListener('keyup', getmovies);
function getmovies(e){
e.preventDefault();
if(e.keyCode === 13){
inputsearch = input.value;
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
getdatalist();
}
}
xhr.open('GET', url + inputsearch + apiId, true);
xhr.send();
}
}
function getdatalist(){
object = JSON.parse(xhr.response);
movieList = object.Search;
movieList.forEach(function(e){
movieId = e.imdbID;
// if i console log here it gives me all the ID's what i want inside this forEach function //
console.log(movieId);
let list = document.createElement('li');
movieDetail = '<img src="'+e.Poster+'" alt="Poster"><h4>'+e.Title+'</h4><button>View More</button>';
list.innerHTML = movieDetail;
ul.appendChild(list);
})
// Here it just give me the last ID of search Result //
console.log(movieId);
getdata();
}
function getdata(){
let vwbtn = document.querySelectorAll('ul li button');
vwbtn.forEach(function(elem){
elem.addEventListener('click', function(){
// i want to get the id of each movie here when i click on selected button//
console.log(movieId);
})
})
}
HTML
<div id="search-div">
<input type="text" placeholder="Search movie">
</div>
<ul id="movie-showcase">
</ul>
<div class="movie-detail">
</div>
我之前在这里问过,但没有得到人们建议我使用LocalStorage的答案,尽管尝试了它,但它仍然存储了最后一个ID。我不知道哪里出了问题。我是一名新程序员,这是我的第一个API项目,因此,如果有人可以帮忙,请提供我,并且我还提供了API密钥,以便任何人都可以检查错误。
答案 0 :(得分:1)
您一直在使用相同的变量,这就是为什么它仅保存最后一个变量的原因。
首先让变量重命名,使其更有意义,因为我们要存储一个movieIdso数组,
var moviesId = [];
您要在此处将其存储为您刚刚获取的所有movieId的数组,
movieList.forEach(function(e){
moviesId.push(e.imdbID);
在您的getdata中,我们调用一个函数来打印您需要的东西,然后将其传递给索引
function getdata() {
let vwbtn = document.querySelectorAll('ul li button');
vwbtn.forEach(function(elem, index){
elem.addEventListener('click', printStuff.bind(null, index) );
})
},
最后是将显示所需信息的printStuff函数
function printStuff(index) {
console.log(moviesId[index]);
}
有很多方法可以解决此问题,这只是其中一种,请随时与我不同意或指出您发现的任何问题