按钮onclick没有响应

时间:2013-12-15 11:40:59

标签: javascript javascript-events image-gallery

我是JavaScript的新手,我正在尝试将自己的图片库作为我的第一个简单项目。我期待它顺利进行,但似乎我在做一些微不足道的错误,我不知道在哪里。

所以,我最初的计划是:我会设置一个空 src 属性的图像元素,创建一个图像名称数组,添加一个函数,它会在任何时候将数组指针增加1触发,然后只需将数组中的相应值添加到 src

但是,它不起作用。你可以试着看看代码中的任何错误吗?我真的不知道该怎么做,只是找不到错误。

<html>
<body>
    <img src="" id="imageCanvas">
    <div id="counterDisplay"></div>

    <script type="text/javascript">
    var images = ["increased.jpg","knight.jpg","knight-g.jpg","golden.jpg","land.jpg"];

    var counterDisplay = document.getElementById("counterDisplay");
    var imageCanvas = document.getElementById("imageCanvas");
    var imageCount = 0;

            // function intended to increase the array position indicator by 1, but it always only increases it in relation to the original imageCount value (0), how to make it save the already increased value?
    function changeCount() {
        imageCount = imageCount+1;
    }

    counterDisplay.innerHTML = imageCount;
    imageCanvas.setAttribute("src",images[imageCount]);

    </script>
            // The main problem: it just refuses to respond!
    <button onclick="changeCount()">NEXT</button>
</body>

非常感谢你。

2 个答案:

答案 0 :(得分:0)

我没有通过这个调试,但我的猜测是正在调用onclick,但你没有更新changeCount代码中的计数。

尝试将几乎所有代码放入changeCount

function changeCount() {
    imageCount = imageCount+1;
    counterDisplay.innerHTML = imageCount;
    imageCanvas.setAttribute("src",images[imageCount]);
}

答案 1 :(得分:0)

单击按钮时会运行此功能。

function changeCount() {
    imageCount = imageCount+1;
}

此代码在脚本首次加载时运行。

counterDisplay.innerHTML = imageCount;
imageCanvas.setAttribute("src",images[imageCount]);

您希望在单击按钮时运行它。将其移到函数内部。