在许多div中插入图像源(最佳方式)

时间:2017-04-27 07:13:02

标签: javascript jquery html

所以我用html& css:

<div id="achterkant">
  <div class="rack">
    <div class="rackRow">
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
    </div>
    <div class="rackRow">
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
    </div>
    <div class="rackRow">
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
    </div>
    <div class="rackRow">
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
    </div>
    <div class="rackRow">
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
    </div>
    <div class="rackRow">
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
      <div class="rackSlot"></div>
    </div>
  </div>
</div>

在所有这些rackSlots中,我需要从我的API(只是一个链接)获得一个图像。我把这些放在一个数组中。有没有办法只使用类rackslot在de first div中插入图像,其中没有图像? 这就是我认为我应该这样做的方式:

   for (i = 0; i < 36; i++){
       $('first rack slot with no images').prepend('<img src="'myarrayofimages[i]'"/>');
   }

1 个答案:

答案 0 :(得分:3)

首先请注意,您的字符串连接存在缺陷 - 您错过了+来加入值。

要实现您的要求,您可以使用:empty:first选择所需的.rackSlot元素:

for (i = 0; i < 36; i++){
  $('.rackSlot:empty:first').prepend('<img src="' + myarrayofimages[i] + '"/>');
}

如果您想让它更精确一点,您可以明确检查它是否包含img元素:

for (i = 0; i < 36; i++){
  $('.rackSlot:not(:has(img)):first').prepend('<img src="' + myarrayofimages[i] + '"/>');
}