简体   繁体   中英

JavaScript - Can I make each image in an array a unique link

I'm very new to JavaScript, and was hoping for some help. I'm trying to build a sliding banner, that has 5 different pictures displayed and rotated simultaneously. I've got that working with 5 versions of this code:

<body onLoad="swapImage2();"/>      <!--Linked with jquery-->

       <script language="JavaScript"> 
var k = 0; var path2 = new Array(); 

// LIST OF IMAGES 
path2[0] = "pics/prime/1r.png"; 
path2[1] = "pics/prime/2r.png"; 
path2[2] = "pics/prime/3r.png"; 
path2[3] = "pics/prime/4r.png";

function swapImage2() 
{ 
document.slider.src = path2[k]; 
if(k < path2.length - 1) k++; 
else k = 0; 
setTimeout("swapImage2()",6000); 
} 
</script> 
<img class="small_banner" name="slider"/> <!-- This is where the image is displayed-->

So the img tags is where the array item is displayed. I need each image in all 5 arrays to have it's own link to various pages in my site. To clarify:

<a href="#"><img class="small_banner" name="slider"/></a>

won't work, since that makes the entire display area one link, where I need pics/prime/1r.png (2r,3r,4r) to each be their own link.

Here's the complete code as I'm using it:http: http://jsfiddle.net/BeaverKing/3wR5f/1/

I know I'm most likely missing something obvious, or perhaps I'm just using the wrong script for the job. If so, could someone suggest a better script?

EDIT:

I've spent the last week looking for a slider that does the job without success. I've tried using the bootstrap carousel, I've tried CarouFredSel, OwlCarousel, TimothySlider, WoW-Slider, CarouselEngine, CircularContentCarousel. None of these work stylistically with what I want, and when I tried to run multiple instances of the script, I was getting conflicts causing the code to break. I'm really not good enough to identify the conflicts in code, so I tried to write one myself. I'm posting my question here as a last resort.

if i undestand right, you need add id attribute to a tag and in swap function set href for it. something like that:

<a href="#" id='link_for_img'><img class="small_banner" name="slider"/></a>

and script

// LIST OF IMAGES WITH PATHS
path2[0] = { img:"pics/prime/1r.png", link: 'pics/prime/1r.png'};
path2[1] = { img:"pics/prime/2r.png", link: 'pics/prime/2r.png'};
path2[2] = { img:"pics/prime/3r.png", link: 'pics/prime/3r.png'};
path2[3] = { img:"pics/prime/4r.png", link: 'pics/prime/4r.png'};

function swapImage2() 
{ 
    document.slider.src = path2[k].img; 
    document.getElementById('link_for_img').href = path2[k].link;
    if(k < path2.length - 1) k++; 
    else k = 0; 
    setTimeout(swapImage2,6000); 
} 

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