如何使用事件侦听器替换数组中的图像?

时间:2019-05-08 23:21:59

标签: javascript arrays image

当单击HTML列表中的图像时,我想将其替换为animals数组中的相应图像。 我该如何选择HTML列表的位置作为数组中的位置?

var images = document.getElementsByTagName("img");
var animals = [
	"images/cheetah.jpg",
	"images/elephant.jpg",
	"images/fish.jpg",
	"images/fox.jpg",
	"images/frog.jpg",
	"images/penguin.jpg",
	"images/sheep.jpg",
	"images/walrus.jpg",
	"images/giraffe.jpg",
	"images/zebra.jpg",
	"images/cheetah.jpg",
	"images/elephant.jpg",
	"images/fish.jpg",
	"images/fox.jpg",
	"images/frog.jpg",
	"images/penguin.jpg",
	"images/sheep.jpg",
	"images/walrus.jpg",
	"images/giraffe.jpg",
	"images/zebra.jpg",];

for (var i =0; i<images.length; i++) {
	    images[i].addEventListener("click", function() {
	    this.src=animals[i];
	    })
    }

0 个答案:

没有答案