显示HTML5 <input type =“file”/>所选图像文件的预览图像

时间:2016-03-16 08:54:31

标签: jquery html image

抱歉,如果问题有误,

我希望display image 标记中的img特定 <input type=file>

$(':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 个答案:

答案 0 :(得分:4)

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

&#13;
&#13;
$(':input[type=file]').change( function(event) {
	var tmppath = URL.createObjectURL(event.target.files[0]);
	$(this).next("img").attr('src',tmppath);
});
&#13;
<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">
&#13;
&#13;
&#13;

有关 .next() .closest()

的更多信息

编辑:由于OP改变了html结构,我在答案中做了一些更改,如下所示。 通过将输入和图像元素放入div并在脚本中进行必要的更改来创建输入和图像元素组。

&#13;
&#13;
$(':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);
});
&#13;
<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>
&#13;
&#13;
&#13;