简体   繁体   English

按钮onclick没有响应

[英]Button onclick doesn't respond

I am fairly new to JavaScript and I am trying to make my own image gallery as my first simple project. 我对JavaScript相当陌生,并且尝试将自己的图片库作为我的第一个简单项目。 I expected it to go smoothly, but it seems like I am doing some trivial mistake, and I have no idea where. 我希望它能顺利进行,但似乎我犯了一些小错误,而且我不知道在哪里。

So, my initial plan was: I would set up an image element with empty src property, create an array of image names, add a function that will increase the array pointer by 1 any time it is triggered, and then just add the corresponding value in the array to the src . 因此,我的初始计划是:我将使用一个空的src属性设置一个图像元素,创建一个图像名称数组,添加一个函数,该函数将在每次触发时将数组指针增加1,然后仅添加相应的值在src的数组中。

It doesn't work, though. 但是,它不起作用。 Could you please try to see any errors in the code? 您能否尝试查看代码中的任何错误? I really have no idea what to do, just can't find a mistake. 我真的不知道该怎么办,只是找不到错误。

<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>

Thank you very much in advance. 提前非常感谢您。

I didn't debug through this, but my guess is that onclick is being called, but you are not updating the count in that changeCount code. 我没有对此进行调试,但是我猜测是正在调用onclick,但是您没有更新该changeCount代码中的计数。

Try putting almost all the code in changeCount . 尝试将几乎所有代码放入changeCount

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

This function runs when the the button is clicked. 单击按钮后,将运行此功能。

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

This code is run when the script first loads. 该代码在脚本首次加载时运行。

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

You want it to run when the button is clicked. 您希望它在单击按钮时运行。 Move it inside the function. 将其移动到函数内部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM