开发者问题收集

显示 HTML5 <input type="file"> 选定图像文件的预览图像

2016-03-16
6258

抱歉,如果问题有误,

<input type=file> 时,我想在 img 标签中 显示 特定的 图像

$(':input[type=file]').change( function(event) {
	var tmppath = URL.createObjectURL(event.target.files[0]);
	$(this).closest("img").attr('src',tmppath);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file1" name="file1">
    <font color="#FF0000">For best view upload only <b>200*250</b></font><div class="clear"></div>
    <img src="" id="img1" class="img1" height="100px" width="100px"><br>
<input type="file" id="file2" name="file2">
    <font color="#FF0000">For best view upload only <b>200*250</b></font><div class="clear"></div>
    <img src="" id="img2" class="img1" height="100px" width="100px"><br>
<input type="file" id="file3" name="file3">
    <font color="#FF0000">For best view upload only <b>200*250</b></font><div class="clear"></div>
    <img src="" id="img3" class="img1" height="100px" width="100px">

这是我的 jsfiddle

1个回答

试试这个:你必须使用 .next() 而不是 .closest() ,因为 next 用于查找下一个元素,而 nearest 用于查找匹配的父元素。参见下面的代码

$(':input[type=file]').change( function(event) {
	var tmppath = URL.createObjectURL(event.target.files[0]);
	$(this).next("img").attr('src',tmppath);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file1" name="file1">
<img src="" id="img1" class="img1" height="100px" width="100px"><br>
<input type="file" id="file2" name="file2">
<img src="" id="img2" class="img1" height="100px" width="100px"><br>
<input type="file" id="file3" name="file3">
<img src="" id="img3" class="img1" height="100px" width="100px">

有关 .next() .closest()

$(':input[type=file]').change( function(event) {
	var tmppath = URL.createObjectURL(event.target.files[0]);
    //get parent using closest and then find img element
	$(this).closest("div").find("img").attr('src',tmppath);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
<input type="file" id="file1" name="file1"><br>
<font color="#FF0000">For best view upload only <b>200*250</b></font><div class="clear"></div>
<img src="" id="img1" class="img1" height="100px" width="100px"><br>
</div>
<div>
<input type="file" id="file2" name="file2"><br>
<font color="#FF0000">For best view upload only <b>200*250</b></font><div class="clear"></div>
<img src="" id="img2" class="img1" height="100px" width="100px"><br>
</div>
<div>
<input type="file" id="file3" name="file3"><br>
<font color="#FF0000">For best view upload only <b>200*250</b></font><div class="clear"></div>
<img src="" id="img3" class="img1" height="100px" width="100px">
</div>
的更多信息
Bhushan Kawadkar
2016-03-16