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

Asked

Viewed 588 times

1

I need to add a different image in a div. I used a for to make this loop. Is there any manipulation that I can do in the img tag that I am adding so that each loop is changed the name of the image?

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>

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

</html>

1 answer

0


In case the names of the images are equal, just concatenate by changing the number. You have to pass the i for a new cloister 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 that 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:

Don’t forget to declare i. Must be for (var i = 0;...

  • Thanks a lot, Sergio! I had actually tried this method of concatenating, but it was working because I put the '+' sign before the variable only. But I corrected it here and it worked. Thanks :)

Browser other questions tagged

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