我创建了一个全局变量,名为 movieID
我有一个函数叫 generateSearch
从API获取数据,然后由 displayResults
函数循环处理结果并在DOM上显示数据。
我的目标是插入一个事件监听器,当你点击一个特定的标题的电影(#more-details
) movieID
变量将采取点击电影的ID!我已经创建了一个全局变量名为movieID,我有一个名为generateSearch的函数,从API中获取数据,然后displayResults函数循环的结果,并显示数据在...
//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()
}
为一个给定的函数设置点击处理程序。
<a href="#" id="more-details" onclick="onTitleClicked('${movie.imdbID}')">
和
function onTitleClicked(id) {
console.info('do here what you want. id:', id);
}
你应该尽量避免使用全局变量。这里有一个解决方案,并在注释中解释。
//EVENT LISTENER
submitBtn.addEventListener('click', event => generateSearch(event.target.value))
document.body.addEventListener('click', event => { // For every click...
const clickedElement = event.target // Get the clicked element
const movieId = clickedElement.dataset.movieId
if (movieId) {
// Do something with the movieId
// ...
}
})
//GENERATE SEARCH DATA
async function generateSearch(query) {
const result = await fetch(`${baseURL}${search}${query}${apiKey}`)
const data = await result.json();
const nodes = getResultsAsArrayOfNodes(data.Search)
//DISPLAY ON UI
// searchResultElement should be a DOM node in which all the results will be appended
searchResultElement.append(...nodes) // Append all the nodes (https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append)
}
function getResultsAsArrayOfNodes(movies) {
return movies.map(movie => { // For each movie...
const node = document.createElement('div') // ...create a node..
node.className = 'results'
const markup = `
<img src="${movie.Poster}" alt="Movie Poster">
<ul>
<!-- Create here an element with an id that contains the IMDB movie id -->
<li><a href="#" data-movie-id="${movie.imdbID}">${movie.Title}</a></li>
<li>${capitalizeFirstLetter(movie.Type)}</li>
<li>${movie.Year}</li>
<li>${movie.imdbID}</li>
</ul>
`
node.innerHTML = markup // ...put the markup in the div.results node
return node // return the node
}) // Return the array of nodes
}
确保你的变量是真正的全局变量
window.movieID = null;
那么你应该可以做到这一点。
<a href="#" id="more-details" onclick="window.movieID = ${movie.imdbID}">