5
I’m trying to load an image through Javascript but it didn’t work. HTML looks like this: <img src="img/bola.jpg/>
, but in Javascript I don’t know.
The code below is to show loading multiple images, but I don’t know why it’s not loading:
Follow the Javascript:
/*
autor : Jose Lemo
descricao: Estudo cinema da baladinha
*/
// true = disponivel, false = indisponivel
window.onload = function(){
carregarPoltronas(); // não está carregando a imagem
}
var poltronas = [false,true,false,true,true,true,false,true,false];
function carregarPoltronas(){
var imagens = document.getElementsByName("img");
for(var i=0; i<imagens.length;i++){
imagens[i].src = "img/disponivel.jpg";
}
}
Follow the xhtml:
<!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 CinemaBaladinha</title>
<style>
div{
margin:0 auto; width:740px; text-align:center;height:250px;
}
#topo {
background:url(img/baladinha.jpg) no-repeat;
}
</style>
<script type = "text/javascript" src = "js/CinemaBaladinha.js"></script>
</head>
<body>
<div id = "topo"></div>
<div>
<img />
<img />
<img />
<img />
</div>
</body>
</html>
Can someone give me an example of how to load an image with Javascript?
Tip: Do not load the image dynamically, it is only complicating. Set a CSS class for when available and add that class to the element. So the image can go in style and not in a tag directly.
– utluiz
However, amend the
src
should work. I suspect that the URL being placed is not right or that code is not running properly for some reason. Inspect the HTML in your browser after opening the page and check that the values are correctly set after execution.– utluiz
This is the problem, tbem is not entering the for. J inspected the xhtml code. hxtml is opening correctly with the image in div #top. The problem is in javascript
– Jose.Lemo
I suspect your line
var imagens = document.getElementsByName("img");
is not returning any element. You search for elements with the attributename="img"
, and in your HTML there is no such element. Try withvar imagens = document.getElementsByTagName("img");
– tayllan
tayllan, Thank you so much :D.Now it worked after q did your procedure above... vlw msmo
– Jose.Lemo
Then Voce will try to show how many armchairs are free or not using that array, like this: https://jsfiddle.net/zy8yp3rw/
– Gabriel Rodrigues