循环div为多个图像

时间:2018-05-25 17:10:38

标签: javascript html image loops

我的问题是我想创建下面div的许多实例,但具有不同的图像属性。我想使用for循环将图像名称增加1。例如:id我想继续增加图像名称中的数字n次。所以在第二次迭代中我希望它是<div class="pm-gallery-post-item-container" style="background-image:url(img/gallery/2nd-white-coat1.jpg);">(注意文件名以2结尾)。

更新: I want to use multiple images for the same kind of div. So instead of creating many divs that are the same but differ with image I want to use a for loop to change the image name

以下是我想要执行此操作的div:

<div class="pm-gallery-post-item-container" style="background-image:url(img/gallery/2nd-white-coat2.jpg);">

1 个答案:

答案 0 :(得分:0)

您可以使用字符串连接为图片网址构建字符串。

var loops = 3;
for (var i = 2; i < (loops + 2); i++) {
  var newElem = $('<div/>').addClass('pm-gallery-post-item-container').css('background-image', 'url(img/gallery/2nd-white-coat' + i + '.jpg)');
  //do something with newElem, such as append to the DOM
}

如果您一次创建div元素,则上述操作将起作用。如果需要多次运行,则需要跟踪下一个数字。有几种方法可以做到这一点。这是一种方式:

$(document).ready(function() {
  var iteration = 2;
  $('#myBtn').on('click', function() {
    var loops = 3;
    for (var i = iteration; i < (loops + iteration); i++) {
      var newElem = $('<div/>').addClass('pm-gallery-post-item-container').css('background-image', 'url(img/gallery/2nd-white-coat' + i + '.jpg)');
    }
    iteration += loops;
    console.log(iteration);
  });
});

用新图片url替换现有div:

$(document).ready(function() {
  $('#myBtn').on('click', function() {
    var existingLi = $('.pm-gallery-post-item-container[style*="background-image:url"]');
    var style = existingLi.attr('style').split('-');
    var number = style[3].match(/\d+/);
    if (number !== null) {
      style[3] = style[3].replace(number, parseInt(number) + 1);
      var newStyle = style.join('-');
      $(existingLi).attr('style', newStyle);
    }
  });
});

小提琴演示:https://jsfiddle.net/zephyr_hex/ok6uv154/