Onclick Image button - Logic not making sense [duplicate]

北慕城南 提交于 2021-01-29 09:05:52

问题


I'm having a very confusing time with this very simple onClick function in Javascript/html. I know there are many questions on this but couldn't quite find an answer given what my script does (Or doesn't in this case). It should be simple but for some reason the logic is just not working as I expect it too.

<h1>The onclick Event</h1>
<img id="onoff" onclick="changeImage();" src="images/Off Button.jpg" width="245" height="238">

<p>Click on button to turn "on"</p>

<script>
    function changeImage() {
        var image = document.getElementById("onoff");
        if (image.src.match("Off Button.jpg")){
            image.src = "images/On Button.jpg";
        }
        else{
            image.src="images/Off Button.jpg";
        }
    }
</script>

So as you can see this should take the original "off button" image and swap it to "on button" when it is clicked provided it is showing the "Off Button.jpg".

However, it does nothing, using the Chrome developer tools I can see the script doesn't even fire. But when I make these changes:

    if (image.src.match("Off Button.jpg")){
        image.src = "images/Off Button.jpg";
    }
    else{
        image.src="images/On Button.jpg";

It now fires and changes the Button to "On Button" but does not fire again to change it back. For me, this makes no sense logically but I might just be missing something really obvious. I know this is pretty basic but any help or explanation would be appreciated.


回答1:


I did some changes to the code and now it's working. I used the relative path with ./ to img src and mostly you should avoid use spaces to name images or anything else - spaces always cause problems ;)

<h1>The onclick Event</h1>
<!-- relative path and no space in name on src -->
<img
    id="onoff"
    onclick="changeImage();"
    src="./images/off-button.jpg" 
    width="245"
    height="238"
/>

<p>Click on button to turn "on"</p>

<script>
    function changeImage() {
        var image = document.getElementById('onoff');
        if (image.src.match('off-button.jpg')) { /*  no space in name */
            image.src = './images/on-button.jpg'; /* relative path and no space 
            in name */
        } else {
            image.src = './images/off-button.jpg'; /* relative path and no space 
            in name */
        }
    }
</script>

Note - Remember to rename the images inside the images folder as well



来源:https://stackoverflow.com/questions/64739799/onclick-image-button-logic-not-making-sense

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!