【发布时间】:2021-03-21 06:33:04
【问题描述】:
我目前正在尝试在两个不同的按钮上设置两个不同的事件,但是,这些按钮 (h1's) 在 forEach() 循环中。长话短说,它是这样的:当点击一个按钮时,文本会出现在它的下面,如果再次点击它就会消失(这到目前为止工作得很好)。现在,我决定添加一个带有动画的 svg,但为此我需要针对特定按钮,因为我需要根据单击的按钮应用不同的 CSS。
我似乎不知道如何为一个按钮设置事件,因为我创建了一个 forEach() 循环,该循环从 HTML 模板中调用按钮和相应的文本。
有没有人可以通过查看这些短代码 sn-ps 来帮助我找到一种方法来整合我在点击 svg/动画方面所缺少的内容?
注意: 下面的 JS 代码 sn-p 目前正在触发我想为按钮 1
function showTours(tours) {
// 1. template clone
const tourTemplate = document.querySelector(".tourTemplate").content;
const tourArea = document.querySelector("#tourArea");
tours.forEach((oneTour) => {
const tourCopy = tourTemplate.cloneNode(true);
tourCopy.querySelector(".tourTitle").textContent = oneTour.title.rendered;
const tourText = tourCopy.querySelector(".tourText");
tourText.textContent = oneTour.description;
//Expand single tour
tourCopy.querySelector(".tourTitle").addEventListener("click", function(){
if (tourText.style.display === "block") {
tourText.style.display = "none";
document.querySelector("#boatSvg").classList.add("show");
document.querySelector("#singleTripArea:nth-of-type(5n)").classList.remove("flashAnimation");
document.querySelector("#singleTripArea:nth-of-type(3n)").classList.remove("flashAnimation");
} else {
tourText.style.display = "block";
document.querySelector("#boatSvg").classList.remove("show");
document.querySelector("#boatSvg").classList.add("boatAnimation");
document.querySelector("#singleTripArea:nth-of-type(5n)").classList.add("flashAnimation");
document.querySelector("#singleTripArea:nth-of-type(3n)").classList.add("flashAnimation");
}
})
tourArea.appendChild(tourCopy);
})
}
【问题讨论】:
标签: javascript loops animation svg foreach