Add a different image in a div to each loop using javascript

1

I need to add a different image to a div. For this I used a for to do this loop. Is there any manipulation I can do in the img tag that I'm adding so that every loop is changed in the image name?

for (i = 0; i <= 16; i++) {

  $('#p' + i).bind('click', function() {
    $(this).html('<img src="images/img1.jpg" border="0";" height="100px"/>');
  });
}
.peca {
  width: 100px;
  height: 100px;
  background-color: #778899;
  float: left;
  margin-left: 5px;
  margin-top: 5px;
  border-radius: 10px;
}

.peca:hover {
  box-shadow: 0 0 5px #000000;
  cursor: pointer;
}
<!DOCTYPE html>
<html>

<head>
  <title>Jogo da Memória</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="style.css">
  <!--Chamando arquivo css externo-->
</head>

<body>

  <div class="tabuleiro">
    <div class="peca" id="p1"></div>
    <div class="peca" id="p2"></div>
    <div class="peca" id="p3"></div>
    <div class="peca" id="p4"></div>
    <div style="clear: both;"></div>
    <!--"Pular linha"-->
    <div class="peca" id="p5"></div>
    <div class="peca" id="p6"></div>
    <div class="peca" id="p7"></div>
    <div class="peca" id="p8"></div>
    <div style="clear: both;"></div>
    <div class="peca" id="p9"></div>
    <div class="peca" id="p10"></div>
    <div class="peca" id="p11"></div>
    <div class="peca" id="p12"></div>
    <div style="clear: both;"></div>
    <div class="peca" id="p13"></div>
    <div class="peca" id="p14"></div>
    <div class="peca" id="p15"></div>
    <div class="peca" id="p16"></div>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script><scripttype="text/javascript" src="script.js"></script>
</body>

</html>
    
asked by anonymous 21.06.2017 / 22:43

1 answer

0

If the names of the images are the same, just changing the number is enough to concatenate. You must pass i to a new clo- sure to stay in memory and not get lost the moment it is used ( more about this here ).

function prepararHTML(nr) {
  return '<img src="images/img' + nr + '.jpg" border="0";" height="100px"/>';
}

for (var i = 0; i <= 16; i++) {
  $('#p' + i).bind('click', function() {
    $(this).html(prepararHTML(i + 1));
  });
}

If they are different names, you can create an array with image names and then iterate over this array:

var imagens = ['foo.jpg', 'bar.jpg'];
function prepararHTML(nr) {
  return '<img src="images/img' + nr + '.jpg" border="0";" height="100px"/>';
}

for (var i = 0; i <= imagens.length; i++) {
  $('#p' + i).bind('click', function() {
    $(this).html(prepararHTML(imagens[i]));
  });
}

Note:

Do not forget to declare i . It should be for (var i = 0;...

    
21.06.2017 / 22:50