I've created a global variable named movieID
and I have a function called generateSearch
which gets data from API and then the displayResults
function loops over the results and displays the data on DOM.
My goal is to insert an event listener which when you click on a specific title of movie (#more-details
) the movieID
variable will take the clicked movie's ID!
//GLOBAL VARIABLES
let resultArr = [];
let movieID;
//EVENT LISTENER
submitBtn.addEventListener('click', generateSearch)
//GENERATE SEARCH DATA
async function generateSearch() {
resultArr = []
const result = await fetch(`${baseURL}${search}${userInput.value}${apiKey}`)
const data = await result.json();
//push data in array
data.Search.forEach(element => {
resultArr.push(element)
})
console.log(resultArr)
displayResults()
}
//DISPLAY ON UI
function displayResults() {
clearUI()
resultArr.forEach(movie => {
const markup = `
<div class="results">
<img src="${movie.Poster}" alt="Movie Poster">
<ul>
<a href="#" id="more-details"><li>${movie.Title}</li></a>
<li>${capitalizeFirstLetter(movie.Type)}</li>
<li>${movie.Year}</li>
<li>${movie.imdbID}</li>
</ul>
</div>
`
resultUI.insertAdjacentHTML('afterbegin', markup)
})
moviePage()
}
将点击处理程序设置为给定的函数:
和
确保您的变量确实是全局变量。
然后,您应该可以执行此操作。