使用数组更改img源代码

时间:2012-05-18 11:24:56

标签: jquery html

我正在尝试使用jQuery更改图像的来源。我想从自动创建的数组中获取新的文件路径。我有数组的代码,但我完全不想尝试在函数中使用数组。

这是我的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
<script src="jquery.js"></script>




<script type="text/javascript">

//create an array that holds all image paths
var picArray = [];

for (var i =1; i <=20; i++) {  // 20 is the number of images
var elemvalue = "images/videoseq_" + format(i) + ".jpg";
picArray[i] = elemvalue;
//alert(picArray)
}

function format(n) { //this function simply adds leading zeros to filenames
n = n.toString(); 
var result;
if (n.length == 4) {result = "0" + n}
if (n.length == 3) {result = "00" + n}
if (n.length == 2) {result = "000" + n}
if (n.length == 1) {result = "0000" + n}
return result;
};
// end image path array creator code


//this function should insert the next imagepath in the array for the image with the class .changeImg
function rightButton(){
    var i;
    var imgPath = $("img .changeImg").attr("src", "picArray[i++]");
    //alert (imgPath);
};

function leftButton(){
    alert('helloleft')
};


//  });





</script>


</head>

<body>

<div id="container">
    <img class="changeImg" src="images/videoseq_00000.jpg" width="1280px" height="720px" />
    <div id="left" onclick="leftButton();"></div>
    <div id="right" onclick="rightButton();"></div>

</div> <!--video -->





</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的代码有两个问题,首先,irightButton函数中没有值,要么将其传入或初始化为您想要的数字(不确定它应该是什么)是)?

其次,您的imgPath变量不需要,JavaScript值在引号中,请参阅:

var imgPath = $("img.changeImg").attr("src", "picArray[i++]");

将您的rightButton代码更改为:

function rightButton(){
    var i = 0; //what should "i" be? Should it be global? I've just put 0 as a placeholder
    $("img.changeImg").prop("src", picArray[i++]);
}