如何允许数组内的不同图像链接到不同的URL网页

时间:2019-02-11 11:20:44

标签: javascript jquery html

我想将数组内的不同图像链接到不同的URL。图像将每2秒随机化一次。但是,我想确保每个图像都有其唯一的URL。到目前为止,我只能链接到一个网址。

需要帮助,谢谢。

//start with id=0 after 2 seconds
var thisId = 0;

$(function(){
	//prepare Your data array with img urls
	var dataArray=new Array();
	dataArray[0]="cat1.jpg";
	dataArray[1]="cat2.jpg";
	dataArray[2]="cat3.jpg";

	window.setInterval(function(){
	var randomNum = Math.floor(Math.random() * dataArray.length);
	
	if (thisId==randomNum){randomNum++;};
	if (randomNum==3){randomNum=0};
	thisId=randomNum;
	
	document.getElementById("thisImg").src = dataArray[randomNum]
	},2000); 
});
<!DOCTYPE html>
<html>
<head>
	<title>Task 2</title>
	
	<!-- calling external js file -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
	<a href="https://www.petco.com/shop/en/petcostore/category/cat" target="_blank"><img id="thisImg" alt="img" src="cat1.jpg" /></a>
	<script src ="Task2.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以使数据成为对象数组,如下所示:

dataArray = [
    {
        image: "cat1.jpg"
        url: "link_for_cat_1.html"
    }
    ...
]

然后,在随机化并选择给定元素后:

document.getElementById("thisImg").src = dataArray[randomNum].image

以类推方式链接

document.getElementById("thisLink").href = dataArray[randomNum].url