forEach只执行一次javascript
我正在使用forEach方法为每个按钮添加一个事件侦听器,第一次一切正常,该函数根据需要调用filterElements函数,但当我第二次尝试单击时,代码没有响应,可能是因为我的HTML集合,我正在使用Array.from转换为一个数组,或者可能是什么forEach只执行一次javascript,javascript,Javascript,我正在使用forEach方法为每个按钮添加一个事件侦听器,第一次一切正常,该函数根据需要调用filterElements函数,但当我第二次尝试单击时,代码没有响应,可能是因为我的HTML集合,我正在使用Array.from转换为一个数组,或者可能是什么 function filterPhotograpsIndividualTages(dataJson) { const individualTags = Array.from(document.getElementsByClassNa
function filterPhotograpsIndividualTages(dataJson) {
const individualTags = Array.from(document.getElementsByClassName('individual-tags'));
individualTags.forEach(btn => btn.addEventListener('click', () => { //this is the forEach method
/*onClick clear the old HTML of photographersDiv and call
the function filterElements to execute his block code!*/
document.getElementById('container').innerHTML = "";
filterElements(dataJson, btn);// function is invoked here
}))
};
// this function is being called inside of the filterPhotograpsIndividualTages function
function filterElements(dataJson, btn){
dataJson.photographers.forEach(photographe => {
if(photographe.tags.indexOf(btn.id) != -1) {
const photographersDiv = document.getElementById('container');
const div = document.createElement("div");
div.innerHTML = `
<div class="photographerContainer">
<a href="photographers.html?id=${photographe.id}">
<div class="portraitBox">
<img src="${photographe.portrait}" alt="photo">
</div>
<h1 class="name">${photographe.name}</h1>
</a>
<p class="city">${photographe.city}, ${photographe.country}</p>
<p class="tagline">${photographe.tagline}</p>
<p class="price">${photographe.price}€/jour</p>
<p class="tags">${photographe.tags.map(tag => `<button id=${tag} class="tag individual-tags">#${tag}</button>`).join(" ")}</p>
</div>
`
photographersDiv.appendChild(div);
}})
};
函数filterPhotograpsIndividualTages(dataJson){
const individualTags=Array.from(document.getElementsByClassName('individualTags');
individualTags.forEach(btn=>btn.addEventListener('click',()=>{//这是forEach方法
/*再次单击清除摄影师div的旧HTML并调用
函数filterElements执行他的块代码*/
document.getElementById('container').innerHTML=“”;
filterElements(dataJson,btn);//函数在这里被调用
}))
};
//正在filterPhotograpsIndividualTages函数内调用此函数
函数filterElements(dataJson,btn){
dataJson.photophers.forEach(摄影师=>{
如果(照片标签索引)(btn.id)!=-1){
const-photophersdiv=document.getElementById('container');
const div=document.createElement(“div”);
div.innerHTML=`
${shopect.city},${shopect.country}
${photograph.tagline}
${photograph.price}€/jour
`
摄影组(儿童组);
}})
};
当您添加这样的事件时,它只绑定到使用GetElementsByCassName选择的DOM,而不绑定到删除后重新添加的DOM
相反,您应该绑定整个文档并检查事件的目标
document.addEventListener('click', function(event) {
if (event.target.classList.contains('your_class')) {
Function();
}
});