替换图片源(错误处理)

时间:2011-04-30 12:44:36

标签: javascript html

嗨我有一个脚本,它会改变图像的来源,即点击图像时webpics / 1.jpg到webpics / 2.jpg。我遇到的一个问题是,在有图像之后脚本仍然可以再用一个图像,所以如果我有11个图像,我可以按下11次并得到一个空图像,我想要的是脚本到运行错误检查并保持当前图像,如果下一个不存在。这是脚本:

$("#prev, #next").click(function() { 
var currentNumber = parseInt($("#image1").attr("src").split('gallery/')[1]); // get the
number
var newNumber = ($(this).attr("id")=="next")?currentNumber+1:currentNumber-1;
var testImage = new Image();
testImage.onload=function() {
var img = $("#image1");
img.attr("src",this.src);
img.css("visibility","visible");   
}
testImage.onerror=function() {
$("#image1").css("visibility","hidden");   
} 
testImage.src="http://www.yogahealth.net.au/gallery/"+newNumber+".jpg";
return false;
});

1 个答案:

答案 0 :(得分:1)

你知道有多少张图片吗?如果是,请测试新数字是否会超过总数(if newNumber ...)并且不执行任何操作(即跳过更改testImage.src的部分。

例如,您需要在变量totalImages中计算总数,然后您可以执行以下操作:

$("#prev, #next").click(function() { 
  var currentNumber = parseInt($("#image1").attr("src").split('gallery/')[1]); // get the   number
  var newNumber = ($(this).attr("id")=="next")?currentNumber+1:currentNumber-1;
  var totalImages = // get the number of total images here
  if ((newNumber > totalImages) || (newNumber <= 0)) {
        return false; // just do nothing
  }

  // here comes the rest of your code
});

请注意,我还添加了您的号码小于0或0的可能性,具体取决于您是否有名为0的图像。如果是,您可以将<=更改为<,否则不会显示0图片。

为了将这个数字添加到您的Javascript代码中,您可以使用PHP呈现代码并使用<?php echo $total; ?>将其插入到脚本中,或者从HTML页面中的其他元素中提取它,就像您使用的那样currentNumber