简体   繁体   中英

How can image in array make to move to link(URL) when it was clicked?

if my html is:

 <div>
 <input type="image" id = "mainImg> <br />
 </div>

 <div>
 <input type="image" class = Button src = "buttonImg.jpg" onclick="showImage()">
 </div>

and my javascript is:

var imgArray = new Array ();
imgArray[0] = "image1.jpg"
imgArray[1] = "image2.jpg"
imgArray[2] = "image3.jpg"
imgArray[3] = "image4.jpg"
imgArray[4] = "image5.jpg"

var linkArray = new Array ();
linkArray[0] = "https://link1.com"
linkArray[1] = "https://link2.com"
linkArray[2] = "https://link3.com"
linkArray[3] = "https://link4.com"
linkArray[4] = "https://link5.com"

function diceCast(){return Math.floor(Math.random()*5);};

function showImage(){
    
    var imgNum = diceCast();
    var objImg = document.getElementById("mainImg");
    objImg.src = imgArray[imgNum];

}

I want to make:

when I click 'imgArray[0]' -> load new page(ex. _blank) 'linkArray[0]'

should I have to make same as 'imgArray[imgNum] = linkArray[linkNum]'? then how can I do?

or teach me how to make that more compact and easier!

Just change the showImage function to set the onclick property.

function showImage(){
    var imgNum = diceCast();
    var objImg = document.getElementById("mainImg");
    objImg.src = imgArray[imgNum];
    objImg.onclick = ()=>window.open(linkArray[imgNum], '_blank');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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