jquery预览图像不起作用

时间:2018-06-17 20:36:27

标签: javascript jquery

所以我试图实现一个预览按钮,这样当我的用户点击上传按钮图像时,他们可以进行预览,但问题是它无法正常工作,我想知道为什么?简要说明:我有一个js函数,可以创建新元素并将其附加到p标签日期。正是在这个函数中将创建预览图像代码



// 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]);
}
&#13;
.uploader {width:50%;height:35%;background:#f3f3f3;border:2px dashed #0091ea;}
&#13;
<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>
&#13;
&#13;
&#13;

如果您运行上面的代码段,则可以看到按钮正在停止,但预览未显示。有人能帮助我吗?

3 个答案:

答案 0 :(得分:3)

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的:

$("#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]);
  }
}

答案 1 :(得分:1)

利用jQuery - 特别是使用

  1. event handlers
  2. delegated event handlers用于动态创建的元素
  3. tree traversal methods
  4. $(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>

    修改

    这个答案是基于你的评论的非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>

答案 2 :(得分:1)

简短

无需在点击时创建元素。 只需添加图像标记并设置默认图像,例如没有选择图像或类似的图像。

以下代码可以帮助您

<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]);
    }
});