简体   繁体   English

如何使用 onclick 和 Javascript 更改图像?

[英]How can I change images with onclick and Javascript?

I know how to change 1 image to another, but I want to know how to change multiple of the same image all to the same image using onclick, but individually.我知道如何将 1 个图像更改为另一个图像,但我想知道如何使用 onclick 将多个相同的图像全部更改为相同的图像,但单独更改。 Like multiple copies of "Image1" should all change to "Image2" when I click on them, but one at a time.就像当我点击“Image1”的多个副本时,它们应该都变成“Image2”,但一次一个。

Give them all the same class, then loop through the elements.给它们所有相同的类,然后循环遍历元素。

 function to60() { var imgs = document.getElementsByClassName('i40'); for (var i = 0; i < imgs.length; ++i) { imgs[i].src = "http://placehold.it/60"; } }
 <div> <img src="http://placehold.it/40" class="i40" onclick="to60()" /> <img src="http://placehold.it/50" class="i50" /> <img src="http://placehold.it/40" class="i40" onclick="to60()" /> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM