Javascript - Image directories

Asked

Viewed 53 times

-4

I am in the following situation: javascript does not find the image in the images/example directory.png

html code:

<html>
    <head>
        <title>Java Script é um barato</title>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <script src="java-script/index-java-script.js"></script>
    </head>
    <body>
        <h3>Clique no interruptor para acender ou apagar a lâmpada</h3>
        <div id="interruptor" onclick ="trocaImg()" >
            <img id="imagemInterruptor" src="imagens/desligado.png">
            <p id="msgInterruptor">Interruptor Desligado</p>
        </div>

        <div id="lampada">
            <img id="imagemLampada" src="imagens/apagada.png">
            <p id="msgLampada">Lâmpada Apagada</p>
        </div>

    </body>
</html>

Javascript code:

var num = 2;
var imglampada = document.getElementById("imagemLampada");
var imginterruptor = document.getElementById("imagemInterruptor");
function trocaImg(){
        setTimeout(function () {
            if (num == 1){
                    imginterruptor.src = "/imagens/ligado.png";
                    imglampada.src = "/imagens/acesa.png";
                    document.getElementById("msgInterruptor").innerHTML = "Interruptor ligado";
                    document.getElementById("msgLampada").innerHTML = "Lampada acesa";
            }else if (num == 2){
                    imginterruptor.src = "/desligado.png";
                    imglampada.src = "/imagens/apagada.png";
                    document.getElementById("msgInterruptor").innerHTML = "Interruptor desligado";
                    document.getElementById("msgLampada").innerHTML = "Lampada apagada";
            }
            //garante que num fique alternando entre 1 e 2
                num = (num % 2) + 1;
        }, 1);
}

imagem da estrutura do diretório

  • try to use ../ instead of / at first, the path is relative, I believe the absolute path will only work if you go up a server

  • I can’t tell if just this one imginterruptor.src = "/desligado.png"; is your problem or if there’s anything else.

  • tried tbm didn’t work, so I put the script in the index itself and it worked without putting .. / or . / or / there left only with images/ off.png

1 answer

-2


Browser other questions tagged

You are not signed in. Login or sign up in order to post.