Method to exchange Javascript / html images

Asked

Viewed 1,188 times

-1

I’m having do with my site swap certain images, I created the following code, someone by chance can point out errors..?

<script type="text/javascript">

                    function ImgsRandom(){

                    var trocar=new Array()

                    trocar[0]='<img src="site.projeto/Logo_pilates.jpg" alt=""/>';

                    trocar[1]='<img src="site.projeto/equipamento.jpg" alt=""/>';

                    trocar[2]='<img src="site.projeto/equipamento_02.jpg" alt=""/>';

                    var whichtrocar=Math.floor(Math.random()*(trocar.length));

                    document.getElementById("imgsrandon").innerHTML = trocar[whichquote];

                    }

                    window.onload=ImgsRandom;

                    </script>
  • The browser already does this, just look at the console of the same that there will be possible error messages.

  • Which error is reported by browser ?

2 answers

0

Well, the mistake you’re trying to find is in the trocar[whichquote] swap for trocar[whichtrocar]. And start analyzing errors by browser with CTRL+SHIFT+I and click on the tab Console there will appear the errors!

0

When accessing the value of the list of images you are using the variable whichquote that until then does not exist, only changing to whichtrocar theoretically it will already work.

Follow an example with just one change, instead of creating an img tag I change the src attribute of an existing image.

  function ImgsRandom()
  {
      // lista de imagens
      var trocar = [
      'http://www.drodd.com/images15/1-4.png',
      'http://www.clker.com/cliparts/f/j/9/x/c/z/blue-rounded-square-with-number-2-md.png',
      'http://ghzwireless.com/live/files/No3-big.png' ];

      // criando valor randômico
      var whichtrocar = Math.floor(Math.random() * (trocar.length));

      // alterando o atributo 'src' da imagem
      document.getElementById("imgsrandon").src = trocar[whichtrocar];
  }

  window.onload = ImgsRandom;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>

<body>
    
    <img id="imgsrandon" />
    
</body>
</html>

Browser other questions tagged

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