首页 > 解决方案 > 通过预览上传来动态更改图像

问题描述

我想要的是- (仅用于图像的所见即所得编辑器)当用户单击我的 html 页面的任何图像时,应该出现“选择文件”按钮选项,而不写任何标签,我不想将该图像上传到服务器所以不需要使用 php 或任何其他只是想预览它。我为实现这一目标所做的一切

//image that already there in html page
<div id="headshot" class="quickFade">
  <img id="blah" src="#" alt="your image" />
</div>
//grab the id of parent element of clicked image
$('img').click(function(event){
  if (event.target.nodeName == 'IMG'){
    var pratik = event.target.parentNode.id; 

// creates <input type="file" id="imgInp">  

var newElem = document.createElement('input');
    newElem.type = "file";      
    newElem.id = "imgInp";

    document.getElementById(pratik).appendChild(newElem);
  }
})

// preview the image after uploading the image and then remove the "choose file" button 
function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#blah').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$('#imgInp').change(function() {

document.getElementById("imgInp").remove();
  readURL(this);
});

整个代码<input type="file" id="imgInp">在下面 动态生成,<img id="blah" src="#" alt="your image" />所以这会像这样

<div id="headshot" class="quickFade">
  <img id="blah" src="#" alt="your image" />
<input type="file" id="imgInp">
</div>

上传过程正在工作,但在预览功能不起作用后预览和删除按钮

但是当我通过编辑 html 文件手动放置此代码时 <input type="file" id="imgInp"> ,然后在预览功能正常工作后删除该按钮。感染功能不依赖于这个代码<input type="file" id="imgInp">位置我的意思是我可以放在任何我想要的地方并且仍然可以预览和删除功能但是当这个代码<input type="file" id="imgInp">是通过上面的 JavaScript 动态出现的代码时,就会出现这个问题

标签: javascriptjquery

解决方案


它不起作用的原因是元素是动态创建的,因此您需要使用事件委托来检测 DOM 中的更改。为此,您可以使用 JQueryon()方法并将委托分配为静态父级。试试这个。

//grab the id of parent element of clicked image
$('img').click(function(event) {
  if (event.target.nodeName == 'IMG') {
    var pratik = event.target.parentNode.id;

    // creates <input type="file" id="imgInp">  

    var newElem = document.createElement('input');
    newElem.type = "file";
    newElem.id = "imgInp";

    document.getElementById(pratik).appendChild(newElem);
  }
})

// preview the image after uploading the image and then remove the "choose file" button 
function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#blah').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

// this is all you need to change
$('#headshot').on('change', '#imgInp', function() {
  document.getElementById("imgInp").remove();
  readURL(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="headshot" class="quickFade">
  <img id="blah" src="https://www.gstatic.com/webp/gallery/1.jpg" alt="your image" />


推荐阅读