如何使用JavaScript更改图像上每次单击时图像标记的URL?

时间:2013-08-24 12:21:38

标签: javascript html arrays loops

我有一个在HTML页面上显示图像的元素。此元素的源是JavaScript数组中许多不同图像之一。 我已经有一个用于循环播放图像的脚本,创建幻灯片效果,但现在我想用按钮手动浏览图像。

到目前为止,这是我的代码,但单击按钮时没有响应。

function nextup() 
{
    imgs = []; 
    imgs[0] = "/snakelane/assets/images/thumb/_1.jpg";  imgs[10] = "/snakelane/assets/images/thumb/_19.jpg"; 
    imgs[1] = "/snakelane/assets/images/thumb/_2.jpg";  imgs[11] = "/snakelane/assets/images/thumb/_20.jpg"; 
    imgs[2] = "/snakelane/assets/images/thumb/_3.jpg";  imgs[12] = "/snakelane/assets/images/thumb/_21.jpg";
    imgs[3] = "/snakelane/assets/images/thumb/_4.jpg";  imgs[13] = "/snakelane/assets/images/thumb/_22.jpg";
    imgs[4] = "/snakelane/assets/images/thumb/_5.jpg";  imgs[14] = "/snakelane/assets/images/thumb/_23.jpg";    
    imgs[5] = "/snakelane/assets/images/thumb/_6.jpg";  imgs[15] = "/snakelane/assets/images/thumb/_24.jpg";
    imgs[6] = "/snakelane/assets/images/thumb/_7.jpg";  imgs[16] = "/snakelane/assets/images/thumb/_25.jpg";
    imgs[7] = "/snakelane/assets/images/thumb/_8.jpg";  imgs[17] = "/snakelane/assets/images/thumb/_26.jpg"; 
    imgs[8] = "/snakelane/assets/images/thumb/_9.jpg";  imgs[18] = "/snakelane/assets/images/thumb/_27.jpg";
    imgs[9] = "/snakelane/assets/images/thumb/_32.jpg"; imgs[19] = "/snakelane/assets/images/thumb/_28.jpg"; 

    var pic = document.getElementById("picbox");

    for(i =0; i < imgs.length; i++) {

        var current = indexOf(pic.src);
        var next = Math.round(current + 1);
        pic.src = imgs[next];
    }
}

有人能告诉我我的代码有什么问题或建议更好的方法吗?

1 个答案:

答案 0 :(得分:2)

您使用过的方法存在多个问题。看看下面的修改功能。如果您需要任何解释,请告诉我。

以下代码将使用包含图像URL的数组,稍后会按顺序将img标记分配给单击。享受!

Here you can try to see the output.

function nextup(){

 //Initialized img array with 10 images, you can do it any way you want to.

 var imgs = []; 
 for(i=0;i<10;i++){
      imgs[i] = "http://lorempixel.com/output/cats-q-c-100-100-"+(i+1)+".jpg";
 }    

 //Fetch the pic DOM element by ID

var pic = document.getElementById("picbox");

//Know what is position of currently assigned image in array.

 var current = imgs.indexOf(pic.src);
 var next = 0; 
 //Handle case if no image is present, the initial case.
 if(current!=-1){
  next = (current + 1)%(imgs.length);
 }

 //Assign the next src
 pic.src = imgs[next];

}
//Scoped outside to call the function first time on load.

nextup();

我在您的代码中发现了以下问题:

  1. 您尝试使用indexOf而未指定必须执行搜索的阵列。想象一下,如果约翰出现在教室而没有指定特定的教室,那么学校的校长会要求某人去查找。
  2. 对于迭代数组,您使用了next变量,如果您需要无限循环,这可能是一个好主意。但是,由于我们限制在10或20张图像,我们需要确保如果当前选择的图像是最后一张图像,我们发现next变为21(假设总共有20张图像。)这将是尝试访问变量越界。
  3. 因此我使用了mod运算符%。 作为JavaScript中的参考,5%10将返回515%10将返回5,依此类推。详细了解mod运营商HERE