如何在JavaScript中使用超链接?

时间:2013-01-20 20:46:35

标签: javascript image

这是我正在旋转的图像列表;

如何单独连接这些图像中的每一个?

在理想的意义上,我想使用这样的东西链接下面的每个图像,我将在下面使用的HTML链接:

<a href="/banners/chiropractor/">banners/chiropractor.jpg></a>

这是我的完整脚本

    <html>
<head>

<script type="text/javascript">
var interval = 2.5; // delay between rotating images (in seconds)
var random_display = 1; // 0 = no, 1 = yes
interval *= 1000;

var image_index = 0;
image_list = new Array();
image_list[image_index++] = new imageItem("banners/chiropractor.jpg");
image_list[image_index++] = new imageItem("banners/chiropody.jpg");
image_list[image_index++] = new imageItem("banners/fitness ball.jpg");
image_list[image_index++] = new imageItem("banners/Dietician.jpg");
image_list[image_index++] = new imageItem("banners/Alexander technique.jpg");
var number_of_image = image_list.length;
function imageItem(image_location) {
this.image_item = new Image();
this.image_item.src = image_location;
}
function get_ImageItemLocation(imageObj) {
return(imageObj.image_item.src)
}
function generate(x, y) {
var range = y - x + 1;
return Math.floor(Math.random() * range) + x;
}
function getNextImage() {
if (random_display) {
    image_index = generate(0, number_of_image-1);
} else {
    image_index = (image_index+1) % number_of_image;
}
var new_image = get_ImageItemLocation(image_list[image_index]);
return(new_image);
}
function rotateImage(place) {
var new_image = getNextImage();
document[place].src = new_image;
var recur_call = "rotateImage('"+place+"')";
setTimeout(recur_call, interval);
}
</script>

</head>

<div>
<img name="rImage" src="banners/chiropractor.jpg" width=222 height=218>
<img name="rImage2" src="banners/chiropractor.jpg" width=222 height=218>
<img name="rImage3" src="banners/chiropractor.jpg" width=222 height=218>
<img name="rImage4" src="banners/chiropractor.jpg" width=222 height=218>
</div>

<script>
rotateImage('rImage');
rotateImage('rImage2');
rotateImage('rImage3');
rotateImage('rImage4');
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的问题并不完全清楚,但如果您希望将图片转换为链接,最简单的方法是将onClick事件处理程序附加到每个图像上,就像这样......

var foo = new imageItem("banners/chiropractor.jpg");
//do whatever else you're doing with it...
foo.onclick = function(){
   self.location.href = "http://someplace.com";
   //or if you want to link to the image itself 
   self.location.href = this.src; //in this case "self" is the window and "this" is the image object.
}