<html>
<body>
<script>
var images_src = ["PrizeImage-1","PrizeImage-2","PrizeImage-3",];
var links = ["Participate1","Participate2","Participate3","Participate4",];
</script>
<a href="random_link" ><img src='random_img' alt='image'></a>
</body>
</html>
如何在单个HTML页面中使用随机图像调用随机链接
答案 0 :(得分:1)
如果要设置图像并使用随机值链接,可以这样做:
HTML
<a href="random_link" id="linkEl"><img id='imgEl' src='random_img' alt='image'></a>
JAVASCRIPT
var Links = ["Link1" , "Link2" , "Link3" , "Link4"];
var images_src = ["Image1" , "Image3" , "Image3" , "Image4"];
var randomLink = Links[parseInt(Math.random()*Links.length)]; //Get random link (with random number from 0 to the link array's length
var randomImage= images_src[parseInt(Math.random()*images_src.length)];//Get random image
var linkEl = document.getElementById('linkEl'); //Get link element
var imgEl = document.getElementById('imgEl'); //Get image eement
linkEl.href = randomLink; //Set the link
imgEl.src = randomImage; //Set the image
要获得更多功能,您应该提供更多详细信息,但这可能会让您有希望。
---编辑---
要将代码重用于多个图像,请将其放在函数
中var Links = ["Link1" , "Link2" , "Link3" , "Link4"];
var images_src = ["Image1" , "Image3" , "Image3" , "Image4"];
function fillRandom(imageId, linkId) {
var randomLink = Links[parseInt(Math.random()*Links.length)]; //Get random link (with random number from 0 to the link array's length
var randomImage= images_src[parseInt(Math.random()*images_src.length)];//Get random image
var linkEl = document.getElementById(linkId); //Get link element
var imgEl = document.getElementById(imageId); //Get image eement
linkEl.href = randomLink; //Set the link
imgEl.src = randomImage; //Set the image
}
然后像你拥有的图像一样多次调用该函数:
fillRandom('imageId', 'linkId');
fillRandom('secondImageId', 'secondLinkId');