因此,我有三个图像,单击它们中的任何一个都应执行相同的功能,我想实现一个可减少当前代码长度的功能。这是代码库的示例:
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 theonclick
function.You could do onclick with
class
instead ofid
您也可以: