我知道为什么会显示错误,因为由于异步,尚未加载按钮。有什么办法可以解决?我无法用言语解释太多。加载时间窗口时,没有按钮,因为它仅在单击id后才出现。我试图放入所有代码,但是堆栈溢出需要很多解释
这是我的主要js代码。取得作品,但我并未提供所有代码。
const controlMovie = async()=> {
const id = window.location.hash.replace('#', '');
if(id){
// new id
clearMovie();
state.control = new Control(id);
await state.control.getMovies();
UImovie(state.control);
}
return id;
};
const viewList = async()=>
{
const id = window.location.hash.replace('#', '');
state.view= new Control(id);
await state.view.getMovies();
UIlist(state.view);
}
['hashchange', 'load'].forEach(event => window.addEventListener(event, controlMovie));
document.querySelector('.add').addEventListener('click', viewList);
这是UI js部分
const UImovie = (info)=> {
const markup = `
<div class="img-fig">
<img src="${info.image}" alt="${info.title}" class="movie-img">
</div>
<div class="movie_details">
<br>
<h3 style="align-items: center; font-weight: bold;"> ${info.title}</h3>
<p>Writer: ${info.writer}</p>
<p>Released date: ${info.year}</p>
<p>Actors: ${info.actors} </p>
<p>imdbRating: ${info.rating}</p>
<p>Total seasons: ${info.seasons}</p>
<p style="font-style: italic; color: red; font-size: 16px;"> "${info.story}"</p>
<button class= "add">+ Add to watchlist</button>
</div>
</div>
`;
document.querySelector('.movies-result').insertAdjacentHTML('afterbegin', markup);
};
const UIlist = (UI)=> {
const markup = `
<h3> ${UI.title} <button class="icons"><ion-icon name="trash"></ion-icon></button></h3>
`;
document.querySelector('.lists').insertAdjacentHTML('afterbegin', markup);
}
答案 0 :(得分:0)
如前所述,根据所提供的代码,将动态添加.icons
。但是.addEventListener
正在页面加载期间执行。因此,在执行时,DOM上没有可用的元素,也没有添加任何侦听器。
您应该尝试改用HTMLElement对象:
const UIlist = (UI)=> {
const h3 = document.createElement('h3');
h3.innerText = UI.title;
const button = document.createElement('button');
const icon = document.createElement('ion-icon');
icon.setAttribute('name', 'trash');
button.append(icon);
button.classList.add('icons');
button.addEventListener('click', function() {
console.log('Button Clicked');
})
h3.append(button)
document.querySelector('.lists').insertAdjacentElement('afterbegin', h3);
}
UIlist( { title: 'Bla' } )
<div>
<div class='lists'></div>
</div>