有没有一种方法可以使用循环对多个图像执行onclick功能?

因此,我有三个图像,单击它们中的任何一个都应执行相同的功能,我想实现一个可减少当前代码长度的功能。这是代码库的示例:

js代码:

    let doorImage1 = document.getElementById('door1')
    let doorImage2 = document.getElementById('door2')
    let doorImage3 = document.getElementById('door3')

    const botDoorPath = "new-url"

    doorImage1.onclick = () => {
      doorImage1.src = botDoorPath
    }

    doorImage2.onclick = () => {
      doorImage2.src = botDoorPath
    }

    doorImage3.onclick = () => {
      doorImage3.src = botDoorPath
    }
评论
闷油瓶
闷油瓶

Changing your code a bit, you can add a class to each image element, let's call it door, after doing this select all elements with that class and loop through it to apply the onclick function.

let doorImages = document.querySelectorAll('.door')

const botDoorPath = "new-url"

for (let i = 0; i < doorImages.length; i++){
  let anImage = doorImages[i]
  anImage.onclick = () => (
      anImage.src = botDoorPath
      )

}
点赞
评论
御林军
御林军

You could do onclick with class instead of id

let doorImage = document.querySelectorAll('.doors') //select all the elem that name of doors
const botDoorPath = "new-url"

doorImage.forEach(elem => elem.addEventListener('click', () => { //loop the elem and assign the click event
  elem.src = botDoorPath;
  console.log(elem)
}))
<img class="doors" id="1" src="3">
<img class="doors" id="2"  src="3">
<img class="doors" id="3"  src="3">
点赞
评论
先生靠过来
先生靠过来

您也可以:

const botDoorPath = "new-url"

document.querySelectorAll( '#door1','#door2','#door3' )
          .forEach(imgElm=>{
            imgElm.onclick=()=> { imgElm.src = botDoorPath }
          })
点赞
评论