Frage

I plan to have 1 image load at one time, and with it, have it's appropriate link. I would like it to write the image into a div with an ID of 'ads'. Here is what I have so far. I'm just not advanced enough in JavaScript in order to make it do what I want :P. Each link array value is the same as the image src array. So img[0] and link[0] belong together.

What I would like it to do is find the image, and then append the URL along with it, so that when the image is clicked, it will go to that site. Any help is appreciated! Thanks!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <style>
        h1 {
            font-size: 32px;
            font-weight: bold;
            color: red;
        }
    </style>
</head>
<body>
    <h1>Reload the page to see different images</h1>
    <h2>Click an image for a link.</h2>
    <div id="ads">
    <!--image link/src here-->
</div>
</body>
</html>


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">


var image = new Array ();
image[0] = "<img src='images/img1.png'></a>";
image[1] = "<img src='images/img2.jpg'></a>";
image[2] = "<img src='images/img3.jpg'></a>";
image[3] = "<img src='images/img4.jpg'></a>";

var link = new Array ();
    link[0] = "<a href='http://www.gooogle.com' target='_blank'>";
    link[1] = "<a href='http://www.shade-designs.com' target='_blank'>";
    link[2] = "<a href='http://www.sharpnackford' target='_blank'>";
    link[3] = "<a href='http://www.donleyford.com' target='_blank'>";

var size = image.length
var x = Math.floor(size*Math.random());
link = x;
document.getElementById('ads').appendChild(link).src=image[x];
</script>
War es hilfreich?

Lösung

If you have anything extra within ads div innerHTML will overwrite it.So better to use append:

$('#ads').append(link[x]+image[x]);

See this Demo

Andere Tipps

Instead of:

link = x;
document.getElementById('ads').appendChild(link).src=image[x];

do:

document.getElementById('ads').innerHTML = link[x] + image[x];
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top