Why are you not loading this image in javascript?

Asked

Viewed 163 times

3

I’m trying to upload these three images in the document but I’m not getting it, does anyone know why not upload?

Follow the xhtml file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">     
    <head> 
        <title> JavaScript Imagens</title>  

        <script type = "text/javascript" src = "js/Imagem.js"> </script>

    </head> 
    <body> 
        <div id ="id">
            <img />
            <img />
            <img />

        </div>
    </body>
</html>

Follow the Javascript file:

window.onload = function(){
    carregarPoltronas();    
}

function carregarPoltronas(){
    // não está carregando estas tres imagens diferentes.
    document.getElementById("id").src= "img/ball_disponivel.jpg";
    document.getElementById("id").src= "img/ball_indisponivel.jpg";
    document.getElementById("id").src= "img/ball_selecionada.jpg";  
} 

1 answer

8


Note that the DOM element that has the id "id" is a div not an image. In other words, you are changing the attribute .src in an element div, and to rewrite the same element.

You can make that right:

function carregarPoltronas() {
    var imagens = document.querySelectorAll("#id > img");
    ["img/ball_disponivel.jpg", "img/ball_indisponivel.jpg", "img/ball_selecionada.jpg"].forEach(function(url, i) {
        imagens[i].src = url;
    });
}

That way you get the right elements with document.querySelectorAll("#id > img"); and then while iterating the urls array, use the callback index to fetch the img sure of the list that the querySelectorAll returns.

Example: https://jsfiddle.net/8cg42ctd/

  • Vlw Sergio Muito obg!

Browser other questions tagged

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