我正在尝试将图像作为输入文件按钮。选择图像后,默认图像将更改为所选图像。
通过使用fileReader
,我只能定位一个图像。
image
中的div
attr?HTML代码
<div class="prep">
<div class="row">
<label>Step 1</label>
<img src="http://png-4.findicons.com/files/icons/129/soft_scraps/256/button_upload_01.png" id="upfile1" style="cursor:pointer" class="img"/ >
<input type="file" class="inputimg" />
</div>
</div>
<span class="add">Add Step</span>
JS代码。
$(document).on("click" ,".img" , function(){
$(this).closest("div").find(".inputimg").trigger("click");
});
var count = 1;
$(".add").on("click",function(){
count ++;
var row = '<div class="row"><label>Step '+count+'</label><img src="http://png-4.findicons.com/files/icons/129/soft_scraps/256/button_upload_01.png" id="upfile1" style="cursor:pointer" class="img"/ ><input type="file" class="inputimg" />';
$(".prep").append(row);
});
$(".inputimg").change(function(){
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
参考我的jsfiddle Demo
谢谢
答案 0 :(得分:1)
是的,显然你可能只需要在适当的层次结构中遍历DOM。
您需要进行两项更改。
将更改事件绑定到新动态创建的元素。
你可以通过在之后添加以下代码来简单地实现它
$(".prep").append(row);
声明
$(".inputimg").change(function () {
readURL(this);
});
realURL()
函数中,您必须更具体
像这样选择$('.img')
将选择所有图像标签和
不仅仅是点击对象附近的那个。那部分可以
已更改为$(input).siblings('.img').attr('src',
e.target.result);
更新1:
关于你的最后一个问题,即关于图片的错位,正如评论中@rageit所提到的,你需要在动态创建的元素中的<label>
和<img>
标记之间添加额外的空格,更新的小提琴反映了这一点。