我有一个数组,其中包含一组由id组成的元素。之前,我将每个元素或数组(例如p)定义为p1,p2,p3等,并且可以正常工作。但是我只想减少代码重用。帮助吗?
我尝试将for循环用于下面的代码作为for循环,但它一直在说输入意外结束
p1.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
//handle click for p2
p2.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
有什么办法可以得到这样的输出:
for ( i=0; i< 25; i++){
p[i].onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;`
}
这是我在HTML中的内容:
<div class="image"><img id="p1" class="portraitImg"
src="../img/portrait/p1.jpeg" alt="Portrait 1" /></div>
<div class="image"><img id="p2" class="portraitImg"
src="../img/portrait/p2.jpeg" alt="Portrait 2" /></div>
答案 0 :(得分:0)
由于您已经拥有类,所以只需使用这些类而不是ID
var imgs = document.getElementsByClassName("portraitImg");
for(var x = 0;x<imgs.length;x++){
imgs[x].addEventListener("click",function(){
document.getElementById("modal").style.display = "block";
document.getElementById("modalImg").src = this.src;
document.getElementById("captionText").innerHTML = this.alt;
});
}
<img src="https://via.placeholder.com/100/09f/AAA.png" alt="1" class="portraitImg"><img src="https://via.placeholder.com/100/000/fff.png" alt="e" class="portraitImg"><img src="https://via.placeholder.com/100/09f/000.png" alt="6" class="portraitImg"><img src="https://via.placeholder.com/100/e33/fff.png" alt="3" class="portraitImg"><img src="https://via.placeholder.com/100/AAA/fff.png" alt="2" class="portraitImg">
<img src="" id="modalImg">
<div id="modal"></div>
<div id="captionText"></div>