【问题标题】:Images not displaying on dynamic generated content图像未显示在动态生成的内容上
【发布时间】:2021-04-15 15:16:27
【问题描述】:

我正在通过动态生成输入字段和图像元素来一次上传多个图像。但是,我的代码不会在动态生成的图像元素上显示图像。

<button type="button" class="btn btn-sm btn-info add-image"><i class="ti-image"></i>  Add image</button>
<br><br>
<div class="images"></div>
$(document).ready(function() {
  var max_image = 10;
  var count = 1;

  $('.add-image').click(function(e) {
    e.preventDefault();
    if (count < max_image) {
      count++;
      $('.images').append(`<div class="input" style="width:100px;height:120px;border:2px dashed lightgrey;float:left;margin:8px">    
        <input type ="file" class ="fileup 1" id ="file'+count+'" style="width:100%; height:100%; opacity:0; position: absolute">    
        <img id ="image'+count+'" src="" style="width:100%; height:100%;">    
        <span class="btn btn-sm btn-danger delete" style="position:relative;bottom:20px"><I class="ti-trash"></i></span>    
      </div>`);

      $(document).on('change', '#file' + count, function() {
        readURL(this);
      });

      function readURL(input) {
        if (input.files && input.files[0]) {
          var reader = new FileReader();
          reader.onload = function(e) {
            $('#image' + count).attr('src', e.target.result);
          }
          reader.readAsDataURL(input.files[0]);
        }
      }
    } else {
      alert("Only a maximum of 10 images is allowed");
    }
  });

  $('.images').on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).parent('div').remove();
    y--;
  })
});

【问题讨论】:

标签: javascript html jquery


【解决方案1】:

可以只使用一个事件处理程序,然后在 readURL 函数中使用 .closest('div').find('img') 将 src 添加到图像标签,而不是为所有文件创建事件处理程序。

演示代码

$(document).ready(function() {
  // allowed maximum input fields
  var max_image = 10;

  // initialize the counter for textbox
  var count = 1;

  // handle click event on Add More button
  $('.add-image').click(function(e) {

    e.preventDefault();

    if (count < max_image) {

      count++; // increment the counter

      // validate the condition

      $('.images').append(`<div class="input" style="width:100px;height:120px;border:2px dashed lightgrey;float:left;margin:8px">

<input type ="file" class ="fileup 1" id ="file'+count+'" style="width:100%; height:100%; opacity:0; position: absolute">

<img id ="image'+count+'" src="" style="width:100%; height:100%;">

<span class="btn btn-sm btn-danger delete" style="position:relative;bottom:20px"><I class="ti-trash"></i></span>

</div>`); // add input field
 } else {
      alert("Only a maximum of 10 images is allowed");
    }
 });

  // handle click event of the remove link
  $('.images').on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).parent('div').remove(); // remove input field
    y--; // decrement the counter
  })
  
  //put this outside..
  $(document).on('change', '.images input[type=file]', function() {
    readURL(this);
  });

  function readURL(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
      //get closest div and then find img add img there
        $(input).closest('div').find('img').attr('src', e.target.result);
      }
      reader.readAsDataURL(input.files[0]);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-sm btn-info add-image"><i class="ti-image"></i>  Add image</button>
<br><br>
<div class="images"></div>

【讨论】:

    【解决方案2】:

    这里有几个问题需要解决。

    • 不要嵌套事件处理程序
    • 将 CSS 规则放在外部样式表中,而不是在 HTML 中内联
    • 您没有使用正确的语法将 count 值附加到模板文字
    • 除上述之外,不要使用增量id 属性。按类对具有共同行为的元素进行分组,并将单个事件处理程序附加到所有元素。这就是您应该对正在使用的委托事件处理程序执行的操作。

    后一点可以解决您的问题,因为它允许您定位被点击的img,并将其特定的src 属性更新为所选文件的内容。

    $(document).ready(function() {
      var max_image = 10;
    
      $(document).on('change', '.fileup', function() {
        readURL(this, $(this).next('img'));
      });
    
      function readURL(input, $target) {
        if (input.files && input.files[0]) {
          var reader = new FileReader();
          reader.onload = function(e) {
            $target.attr('src', e.target.result);
          }
          reader.readAsDataURL(input.files[0]);
        }
      }
    
      $('.add-image').click(function(e) {
        e.preventDefault();
    
        if ($('div.input').length < max_image) {
          $('.images').append(`<div class="input">
            <input type="file" class="fileup" />
            <img />
            <span class="btn btn-sm btn-danger delete">
              <i class="ti-trash">X</i>
            </span>
          </div>`);
        } else {
          alert("Only a maximum of 10 images is allowed");
        }
      });
    
      $('.images').on("click", ".delete", function(e) {
        e.preventDefault();
        $(this).closest('div').remove();
      })
    });
    div.input {
      width: 100px;
      height: 120px;
      border: 2px dashed lightgrey;
      float: left;
      margin: 8px;
    }
    
    input.fileup {
      width: 100%;
      height: 100%;
      opacity: 0;
      position: absolute;
    }
    
    div.input img {
      width: 100%;
      height: 100%;
    }
    
    span.delete {
      position: relative;
      bottom: 20px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button type="button" class="btn btn-sm btn-info add-image">
      <i class="ti-image"></i>  
      Add image
    </button>
    <br><br>
    <div class="images"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多