日期:2014-05-16  浏览次数:20322 次

出问题了!JavaScript数组实现点击图片显示下一张效果
js代码如下:
JScript code

var image = new Array();
image[0]= "image/2.jpg";
image[1]= "image/A.jpg";
image[2]= "image/B.jpg";
image[3]= "image/C.jpg";
image[4]= "image/D.jpg";
image[5]= "image/E.jpg";
image[6]= "image/F.jpg";
function showPic() {
var pic = document.getElementById("picture");
var source = pic.getAttribute("src");
for(i=0;i<image.length;i++){
        if(source == image[i]){
        source=image[i+1];
        pic.setAttribute("src",source);}
}
}


html页面中img部分如下
HTML code

<img  onclick="showPic(this);" src="image/2.jpg" alt="tupian"  id="picture" />



图片保存在image文件夹中分别为 2.jpg A.jpg B.jpg C.jpg D.jpg E.jpg F.jpg 但是有问题,无法按预想效果显示 求高手指导!

------解决方案--------------------
本地测试可以这么做,上面的函数还有点问题,需要加上break;语句跳出for循环:

HTML code
<!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>无标题文档</title>
<script type="text/javascript">
var image = new Array();
image[0]= "image/2.jpg";
image[1]= "image/A.jpg";
image[2]= "image/B.jpg";
image[3]= "image/C.jpg";
image[4]= "image/D.jpg";
image[5]= "image/E.jpg";
image[6]= "image/F.jpg";

function showPic() {
    var pic = document.getElementById("picture");
    var source = pic.src
    for (i = 0; i < image.length; i++) {
        if (source.indexOf(image[i]) != -1) {
            source = image[(i + 1) % image.length];
            pic.src = source;
            break;
        }
    }
}


</script>
</head>

<body>
<img onclick="showPic(this);" src="image/2.jpg" alt="tupian"  id="picture" />
</body>
</html>

------解决方案--------------------
JScript code

    var image = new Array();
    image[0]= "images/1.jpg";
    image[1]= "images/2.jpg";
    image[2]= "images/3.jpg";
    image[3]= "images/4.jpg";
    image[4]= "images5.jpg";
    image[5]= "images/6.jpg";
    image[6]= "images/7.jpg";
    function showPic() {
        var pic = document.getElementById("picture");
        var source = pic.getAttribute("src");
        for(var i=0;i<image.length;i++){
            if(source == image[i]){
                source=image[i+1];
                pic.setAttribute("src",source);
                break;
            }
        }
    }