1

Подскажите пожалуйста, как я могу присвоить data-id='i' элементу <div> с background локального фото?

$(function() {
  var imagesPreview = function(input, placeToInsertImagePreview) {
    if (input.files) {
      var filesAmount = input.files.length;
      for (i = 0; i < filesAmount; i++) {
        var reader = new FileReader();
        reader.onload = function(event) {
          $($.parseHTML("<div class='add_photo' data-id=''>")).css("background", "url(" + event.target.result + ")").appendTo(placeToInsertImagePreview);
        }
        console.log(i);
        reader.readAsDataURL(input.files[i]);
      }
    }
  };
  $('#gallery-photo-add').on('change', function() {
    imagesPreview(this, '#photo_add_preview');
  });
});
.add_photo {
  width: 100px;
  height: 100px;
  background-size: cover!important;
  background-position: center!important;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="gallery-photo-add">
      <span aria-hidden="true">Загрузить</span>
      <input type="file" multiple id="gallery-photo-add" style="display:none" accept="image/*">
</label>
<div id="photo_add_preview"></div>

1

1 ответ 1

1

Не знаю в чём проблема. Объявляете переменную в цикле через let и спокойно подставляете:

$(function() {
  var imagesPreview = function(input, placeToInsertImagePreview) {
    if (input.files) {
      var filesAmount = input.files.length;
      for (let i = 0; i < filesAmount; i++) {
        var reader = new FileReader();
        reader.onload = function(event) {
          $($.parseHTML("<div class='add_photo' data-id='" + i + "'>")).css("background", "url(" + event.target.result + ")").appendTo(placeToInsertImagePreview);
        }
        console.log(i);
        reader.readAsDataURL(input.files[i]);
      }
    }
  };
  $('#gallery-photo-add').on('change', function() {
    imagesPreview(this, '#photo_add_preview');
  });
});
.add_photo {
  width: 100px;
  height: 100px;
  background-size: cover!important;
  background-position: center!important;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="gallery-photo-add">
      <span aria-hidden="true">Загрузить</span>
      <input type="file" multiple id="gallery-photo-add" style="display:none" accept="image/*">
</label>
<div id="photo_add_preview"></div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.