[英]How can I access the index of the clicked item?
I'm building a shop section for a school project.我正在为一个学校项目建立一个商店部分。 It works like a gallery: when clicking on an card, a new display opens up with fullscreen info about the product: img, product title, price... I've managed to match the image of the fullscreen display to the one clicked (you won't see the images since it's a relative URL).它就像一个画廊:当点击一张卡片时,一个新的显示打开了关于产品的全屏信息:img,产品标题,价格......我已经设法将全屏显示的图像与点击的图像相匹配(你不会看到图像,因为它是一个相对 URL)。
Now I need to match the rest of the info.现在我需要匹配信息的 rest。
const miniaturas = document.querySelectorAll(".galeria a");
const modal = document.querySelector(".modal");
const imgModal = document.querySelector(".modal img");
const plantNames = document.querySelectorAll(".galeria h3")
const plantNameModal = document.querySelector(".modal h3");
miniaturas.forEach(function(miniatura){
miniatura.addEventListener("click", function(evento){
evento.preventDefault();
imgModal.setAttribute("src",miniatura.getAttribute("href"));
modal.classList.add("visible");
for(i = 0; i < miniaturas.length; i++){
plantNameModal.innerHTML = plantNames[i].innerHTML;
}
})
})
modal.addEventListener("click", function(){
modal.classList.remove("visible");
})
I don't know how to get the innerHTML via each item's index.我不知道如何通过每个项目的索引获取 innerHTML。 I've tried using a for loop and the parameter "miniatura" from the function. CodePen here.我尝试使用 for 循环和来自 function.CodePen 的参数“miniatura” 。
You can get the index of each miniatura
as the second argument to the handler function you pass to the forEach
.您可以获得每个miniatura
图的索引作为传递给forEach
的处理程序 function 的第二个参数。 You have access to this index within the body of the addEventListener
, as in:您可以在addEventListener
的主体中访问此索引,如下所示:
miniaturas.forEach(function(miniatura, index){
miniatura.addEventListener("click", function(evento){
evento.preventDefault();
imgModal.setAttribute("src",miniatura.getAttribute("href"));
modal.classList.add("visible");
// instead of for loop, use `index` to access
// the corresponding elements in the arrays:
plantNameModal.innerHTML = plantNames[index].innerHTML;
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.