在与输入相同的父项下的img元素中预览所选图像

时间:2018-11-20 20:33:56

标签: javascript jquery

在那些div中,我有几个div,它们的输入类型是文件。我使用CSS隐藏了输入元素,并使div onclick输入了click。因此,如果有人单击div,则实际上单击了文件选择器。我搜索了许多网站和stackoverflow,试图按照说明在上传之前显示预览,但似乎对我不起作用或我犯了错误(浏览器控制台未显示错误)。你们能帮我弄清楚我遇到了什么问题吗?谢谢

		jQuery( document ).ready(function($) {	

let uploaders_divs = document.getElementsByClassName("each_angle_wrapper");
	Object.entries(uploaders_divs).map(( object ) => {
		
		
  object[1].addEventListener('click', function (e) {
$( this ).find( ".file_upload" ).click();

});

});




let uploaders = document.getElementsByClassName("file_upload");
	Object.entries(uploaders).map(( object1 ) => {
		
object1[1].addEventListener('change', function (e) {
	var selector = $(this);
 if (selector.files && selector.files[0]) {
        var reader = new FileReader();
        
        reader.onload = function (e) {
            selector.parent().find( "img" ).attr('src', e.target.result);
        }
        reader.readAsDataURL(selector.files[0]);
    }
	
});
});





});
.each_angle_wrapper {
	float: left;
	display: block;
	height: 350px;
	margin-right: 35px;
}
	.each_angle_wrapper img {
max-width: 400px;
}
.file_upload {
	display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="each_angle_wrapper">
	First Picture: <br>
	<input type="file" class="file_upload" id="first_pic_ext" name="pic1" accept="image/*"/>
	<img src="https://app.wizpi360.com/assets/img/Inventory/Editor/img_up.png" />
	</div>
	


			<div class="each_angle_wrapper">
	Second Picture:<br>
	<input type="file" class="file_upload" id="second_pic_ext" name="pic2" accept="image/*"/>
	<img src="https://app.wizpi360.com/assets/img/Inventory/Editor/img_up.png" />
	</div>

1 个答案:

答案 0 :(得分:0)

决定做出此回答,因为有很多错误。但是没关系!我们都在这里学习。我删除了纯JS代码,因为我们已经在使用jQuery并且它更易于使用。下面是我们使用jQuery制作事件监听器后的代码,并附有注释以帮助您了解发生了什么。

下面的代码应该对您有用。

jQuery( document ).ready(function($) {
  // creates a click event listener on all the images
  $('.each_angle_wrapper img').click(function() {
    // clicks on the respective input
    $(this).parent().find('input').click();
  });
  // creates an onchange event listener for all the inputs
  $('.file_upload').change(function() {
    // holds scope for this input
    var selector = $(this);
    // selector[0] references the direct element without jQuery since we need to access the files object inside of it
    if (selector[0].files && selector[0].files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        selector.parent().find( "img" ).attr('src', e.target.result);
      }
      reader.readAsDataURL(selector[0].files[0]);
    }   
  });
});