Why are not you loading this image in javascript?

3

I'm trying to load these three images into the document but I can not, does anyone know why it does not load?

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";  
} 
    
asked by anonymous 25.04.2016 / 07:11

1 answer

8

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

You can do this to fix this:

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;
    });
}

In this way you will get the right elements with document.querySelectorAll("#id > img"); and then while you iterate the urls array, you use the callback index to fetch the img from the list that querySelectorAll returns.

Example: link

    
25.04.2016 / 07:23