图像滑块JavaScript

时间:2019-04-21 11:06:55

标签: javascript html

我编写了这段代码,但是下一个按钮不起作用,它显示错误无法设置未定义的属性'src'

<script language="javascript" >
    var pics=new Array("img1.jpeg","img2.jpg","img3.jpg","img4.jpg","img5.jpg");
    var count=0; var len=pics.length;
    function next() {
        // body...
        count++;
        if (count<len) {
            document.pic.src=pics[count];
        }
        else{
            count=0;
            document.pic.src=pics[count];
        }
    }
    function changePic(imgSrc) {
    document.getElementById("pic").src=imgSrc;

}
</script>

当我单击“下一步”按钮时,它将显示滑动条中的下一张图像

1 个答案:

答案 0 :(得分:0)

  1. document.getElementById("pic")而不是document.pic来做。document.id以元素为目标不是一个好习惯

或使用 changePic(pics[count])

var pics=new Array("img1.jpeg","img2.jpg","img3.jpg","img4.jpg","img5.jpg");
    var count=0; var len=pics.length;
    function next() {
        // body...
        count++;
        if (count<len) {
            document.getElementById("pic").src=pics[count];
            //OR
            changePic(pics[count]);
        }
        else{
            count=0;
            document.getElementById("pic").src=pics[count];
            //OR
             changePic(pics[count]);
        }
    }
    function changePic(imgSrc) {
      document.getElementById("pic").src=imgSrc;
    }