我使用jQuery动态添加表单组:
<form>
<div id="form-group-wrapper">
<div class="row">
<input class="userfile" name="userfile[]">
<img src="default.png" class="preview-image" />
</div>
</div>
<button type="submit">POST</button>
<button type="button" id="copy-btn">Add new row</button>
</form>
<div id="hide-ele">
<div class="row">
<input class="userfile" name="userfile[]">
<img src="default.png" class="preview-image" />
</div>
</div>
jQuery是:
$('#copy-btn').click(function(){
newOne = $('#hide-ele').html();
$('#form-group-wrapper').append(newOne);
});
$(function() {
$(".userfile").on("change", function() {
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return;
if (/^image/.test( files[0].type)){
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onloadend = function(){
$(".preview-image").attr('src', this.result);
}
}
});
});
当我通过点击&#34;添加新行&#34;创建新表单组时按钮,它无法预览所选图像。 知道如何解决这个问题吗? 感谢。
答案 0 :(得分:2)
添加新元素后,我们必须将change
事件绑定到它们。请尝试以下代码。
function imagePreview() {
$(".userfile").unbind('change').bind("change", function() {
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return;
if (/^image/.test( files[0].type)){
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onloadend = function(){
//Changed below line as well to show preview next to the changed element
$(this).next(".preview-image").attr('src', this.result);
}
}
});
}
$('#copy-btn').click(function(){
newOne = $('#hide-ele').html();
$('#form-group-wrapper').append(newOne);
imagePreview();
});
$(function() {
imagePreview();
});