简体   繁体   English

jQuery预览图像不起作用

[英]jquery preview image not working

So I'm trying to implement a preview button so that when my users clicks on the upload button image they could have a preview but the thing is that it is not working, I wonder why ?? 因此,我正在尝试实现一个预览按钮,以便当我的用户单击上传按钮图像时,他们可以进行预览,但事实是它不起作用,我想知道为什么吗? A brief description : I have a js function that creates new elements and append it to ap tag date. 简要说明:我有一个js函数,它创建新元素并将其附加到ap tag date。 It is in this function that is going to create the preview image code 正是在此功能中将创建预览图像代码

 // code for creating new elements function createElements(){ const userQuestions = document.querySelector('#userQuestions'); userQuestions.insertAdjacentHTML( 'beforeend', '<div class="uploader" onclick="$(\\'#filePhoto\\').click()"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" id="filePhoto" style="display:block;width:185px;" /></center><div class="grid-container">' ); } ///Code to preview image function handleImage(e) { var imageLoader = document.getElementById('filePhoto'); imageLoader.addEventListener('change', handleImage, false); var reader = new FileReader(); reader.onload = function (event) { $('.uploader').html( '<img width="300px" height="350px" src="'+event.target.result+'"/>' ); } reader.readAsDataURL(e.target.files[0]); } 
 .uploader {width:50%;height:35%;background:#f3f3f3;border:2px dashed #0091ea;} 
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="userQuestions"></div> <button type="button" onclick="createElements()">add elements</button> </body> </html> 

If you run the snippet above you can see that the button is woeking but the preview is not showing. 如果运行上面的代码段,则可以看到该按钮正在摇动,但未显示预览。 Could someone help me? 有人可以帮我吗?

HTML: HTML:

<div class="row">
  <div class="col-xs-4">
    <div class="form-group">
      <label>Company Logo</label>
      <input type="file" class="form-control" value="" name="companyLogo" id="companyLogo" accept="image/*" />
    </div>
  </div>
  <div id="displayImage">
     <img id="imgData" src="#" alt="your image" height="150px" width="150px" />
  </div>
</div>

JavaScript: JavaScript:

$("#companyLogo").change(function(e) {
  if(e.target.value === "") {
    $("#displayImage").hide();
  } else {
    $("#displayImage").show();
  }
  readURL(this);
});

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $("#imgData").attr("src", e.target.result);
    }
    reader.readAsDataURL(input.files[0]);
  }
}

Short n simple 短n简单

No need to create an element on click. 无需在点击时创建元素。 Just add an image tag and set a default image like no image selected or something like that. 只需添加图片标签并设置默认图片,例如未选择图片或类似图片即可。

The following code will help you 以下代码将为您提供帮助

<input type="file" name="myCutomfile" id="myCutomfile"/>


<img id="customTargetImg" src="default.jpg" width="400" height="250">

$("#myCutomfile").change(function() {    
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#customTargetImg').attr('src', e.target.result);
        }
        reader.readAsDataURL(this.files[0]);
    }
});

Take advantage of jQuery -- particularly using 利用jQuery-特别是使用

  1. event handlers 事件处理程序
  2. delegated event handlers for dynamically-created elements 动态创建元素的委托事件处理程序
  3. tree traversal methods . 树遍历方法

 $(function() { var userQuestions = $('#userQuestions'); // create onclick event handler for your button $('#addElements').click(function() { // IDs must be unique - since you can have an arbitrary number of filePhoto, use a class instead userQuestions.append( '<div class="uploader"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" class="filePhoto" /><div class="grid-container"></div>' ); }); // create delegated onclick event handler for your .uploader userQuestions.on('click', '.uploader', function() { // you only want to target the file input immediately after it $(this).next('[type=file]').click(); }); // create delegated onchange event handler for your .filePhoto userQuestions.on('change', '.filePhoto', function() { // find related uploader var uploader = $(this).prev('.uploader'); // check file was given if (this.files && this.files.length) { var reader = new FileReader(); reader.onload = function(event) { uploader.html('<img width="300px" height="350px" src="' + event.target.result + '"/>'); } reader.readAsDataURL(this.files[0]); } }); }); 
 .uploader { width: 50%; height: 35%; background: #f3f3f3; border: 2px dashed #0091ea; } .filePhoto { display: block; width: 185px; } 
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="userQuestions"></div> <!-- added ID attribute --> <button type="button" id="addElements">add elements</button> </body> </html> 

Edit 编辑

This answer is a non-jQuery solution based off your comment. 这个答案是基于您的评论的非jQuery解决方案。

 // code for creating new elements function createElements() { // no need to document.querySelector if the selector is an ID const userQuestions = document.getElementById('userQuestions'); // you want to use onclick/onchange attributes here as they are dynamically created userQuestions.insertAdjacentHTML( 'beforeend', '<div class="uploader" onclick="selectFile(this)"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" onchange="handleImage(this)" />' ); } // trigger click on file input that follows the uploader function selectFile(uploader) { uploader.nextSibling.click(); } ///Code to preview image function handleImage(input) { if (input.files.length) { var reader = new FileReader(); reader.onload = function(e) { input.previousSibling.innerHTML = '<img width="300px" height="350px" src="' + e.target.result + '"/>'; } reader.readAsDataURL(input.files[0]); } } 
 .uploader { width: 50%; height: 35%; background: #f3f3f3; border: 2px dashed #0091ea; } .filePhoto { display: block; width: 185px; } 
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="userQuestions"></div> <button type="button" onclick="createElements()">add elements</button> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM