Как повторно использовать код загрузки jQuery для эскизов 2 и 3 - PullRequest
1 голос
/ 07 августа 2020

Приложение, которое я создаю, имеет три входных файла [type = "file"]. Первый ввод для загрузки нацелен на эскиз 1, второй ввод для загрузки нацелен на второй эскиз, et c. Код загрузки jQuery работает для первого эскиза. Есть ли способ сделать код повторно используемым для эскизов 2 и 3 без повторения кода?

$(window).on('load', function() {
  var files = $("input[type=file]");
  files.change(function(e) {
    if (this.files && this.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
        $(".thumbnail-one img").attr("src", e.target.result);
        $('.full-image img').attr("src", e.target.result);
      }
      reader.readAsDataURL(this.files[0]);
    }
  });
});

$(document).ready(function() {
  $('.box').click(function() {
    $('.full-image').html($(this).html());
    console.log(this);
  });
});
body {
  font-family: 'Poppins', Verdana, Arial, sans-serif;
}

fieldset {
  background-color: lavender;
  border: 10px solid darkblue;
  border-radius: 20px;
  margin: 20px auto;
  width: 720px;
}

legend {
  background-color: purple;
  border-radius: 10px;
  color: white;
  padding: 12px;
}

fieldset div {
  margin: 10px;
}

label {
  display: inline-block;
  text-align: right;
  vertical-align: top;
  width: 200px;
}

.container {
  width: 60%;
  overflow: hidden;
  margin: 100px auto;
}

.box {
  width: 100px;
  height: auto;
  padding: 10px;
}

.box {
  cursor: pointer;
}

.full-image {
  width: 580px;
  height: 580px;
  padding: 10px;
}

.col {
  float: right;
}

.full-image img {
  width: 100%;
  /* height: 100%; */
}

.closebtn {
  position: absolute;
  top: 10px;
  right: 15px;
  color: white;
  font-size: 35px;
  cursor: pointer;
}
image

Ответы [ 2 ]

1 голос
/ 07 августа 2020

function imgUploaded(event, thumbnail){
    var fileInput = event.target;
    if (fileInput.files && fileInput.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
        $("." +thumbnail +" img").attr("src", e.target.result);
        $('.full-image img').attr("src", e.target.result);
      }
      reader.readAsDataURL(fileInput.files[0]);
  }
}


$(document).ready(function() {
  $('.box').click(function() {
    $('.full-image').html($(this).html());
  });
});
body {
  font-family: 'Poppins', Verdana, Arial, sans-serif;
}

fieldset {
  background-color: lavender;
  border: 10px solid darkblue;
  border-radius: 20px;
  margin: 20px auto;
  width: 720px;
}

legend {
  background-color: purple;
  border-radius: 10px;
  color: white;
  padding: 12px;
}

fieldset div {
  margin: 10px;
}

label {
  display: inline-block;
  text-align: right;
  vertical-align: top;
  width: 200px;
}

.container {
  width: 60%;
  overflow: hidden;
  margin: 100px auto;
}

.box {
  width: 100px;
  height: auto;
  padding: 10px;
}

.box {
  cursor: pointer;
}

.full-image {
  width: 580px;
  height: 580px;
  padding: 10px;
}

.col {
  float: right;
}

.full-image img {
  width: 100%;
  /* height: 100%; */
}

.closebtn {
  position: absolute;
  top: 10px;
  right: 15px;
  color: white;
  font-size: 35px;
  cursor: pointer;
}
image
0 голосов
/ 07 августа 2020
  1. Добавьте новый attribute data-thumb к вашему вводу и добавьте соответствующий класс эскизов здесь, например data-thumb='thumbnail-one' data-thumb='thumbnail-two'. Ваш ввод будет выглядеть как <input type="file" id="avatar" name="avatar" data-thumb='one' required="">

  2. Используйте let thumb = $(this).data('thumb');, чтобы получить значение класса миниатюр внутри files.change(function(e) {...}. Примечание вы также можете использовать let thumb = $(this).attr('data-thumb');.

  3. Используйте $("." + thumb + " img").attr("src", e.target.result); в качестве селектора.

PS Как упоминалось @AlwaysHelping в комментарии, а также в соответствии с рекомендациями, вы всегда должны использовать уникальные значения id. Потому что, если вы используете #avatar, он всегда будет возвращать элемент first в DOM с id = avatar. Также в форме postback это может вызвать проблему.

$(window).on('load', function() {
  var files = $("input[type=file]");
  files.change(function(e) {
    if (this.files && this.files[0]) {
      let thumb = $(this).data('thumb');
      // let thumb = $(this).attr('data-thumb'); // alternative to above line.
      var reader = new FileReader();
      reader.onload = function(e) {
        $("." + thumb + " img").attr("src", e.target.result);
        $('.full-image img').attr("src", e.target.result);
      }
      reader.readAsDataURL(this.files[0]);
    }
  });
});

$(document).ready(function() {
  $('.box').click(function() {
    $('.full-image').html($(this).html());
    console.log(this);
  });
});
body {
  font-family: 'Poppins', Verdana, Arial, sans-serif;
}

fieldset {
  background-color: lavender;
  border: 10px solid darkblue;
  border-radius: 20px;
  margin: 20px auto;
  width: 720px;
}

legend {
  background-color: purple;
  border-radius: 10px;
  color: white;
  padding: 12px;
}

fieldset div {
  margin: 10px;
}

label {
  display: inline-block;
  text-align: right;
  vertical-align: top;
  width: 200px;
}

.container {
  width: 60%;
  overflow: hidden;
  margin: 100px auto;
}

.box {
  width: 100px;
  height: auto;
  padding: 10px;
}

.box {
  cursor: pointer;
}

.full-image {
  width: 580px;
  height: 580px;
  padding: 10px;
}

.col {
  float: right;
}

.full-image img {
  width: 100%;
  /* height: 100%; */
}

.closebtn {
  position: absolute;
  top: 10px;
  right: 15px;
  color: white;
  font-size: 35px;
  cursor: pointer;
}
image
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...