我正在动态创建选项卡,并在每个选项卡上显示一个图像。然后我允许选择一个新的图像来替换它。在第一个选项卡上选择新图像时,将显示新图像(显示的原始图像将被替换)。但是,在后续选项卡上,不会替换原始图像(显示新图像名称)。控制台中没有错误。
所以在我的研究中我找到了解决方案"$(document).on“。我可以在我的日期和按钮上使用它(类似的问题)。然而,我不能让它为我的图像选择工作。这是我的代码,也是我尝试过的:
//I have changed this:
// $("#photo").change(function(){
// readURL(this);
// });
$(document).on('change', '#photo', function(){
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#campImage').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
//I have tried this and it does not display the image even on the first tab:
// function readURL(input) {
// if (input.files && input.files[0]) {
// var reader = new FileReader();
//
// $(document).on('onload', 'reader', function(e) {
// $('#campImage').attr('src', e.target.result);
// })
//
// reader.readAsDataURL(input.files[0]);
// }
// }
HTML:
//Column 2 to contain the image
contents += '<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">';
contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="photo">Photograph:</label>';
contents += '<input class="form-control-file col-lg-8 col-md-8 col-sm-8 col-xs-8" type="file" id="photo" name="photo" placeholder="Photograph">';
contents += '<img id="campImage" src="' + obj.eventPicture + '" alt="Camp image" class="img-thumbnail">';
contents += '</div>';
发布于 2018-08-03 08:44:13
解决这个问题的方法是让每个"id=“都是唯一的。在这种情况下,id="photo“需要更改为"id="'+obj.eventId+'"‘’,而”id=“campImage”“更改为”id=“campImage‘+obj.eventId+’”.The eventId是表中该行的主键,因此是唯一的。
代码是:
//Column 2 to contain the image
contents += '<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">';
contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="'+obj.eventId+'">Photograph:</label>';
contents += '<input class="form-control-file col-lg-8 col-md-8 col-sm-8 col-xs-8 photo-input" type="file" id="'+obj.eventId+'" name="photo" placeholder="Photograph">';
contents += '<img id="campImage'+obj.eventId+'" src="' + obj.eventPicture + '" alt="Camp image" class="img-thumbnail">';
contents += '</div>';
所以你现在问,如果"id“每次都改变,我如何识别它已经改变了?在类中添加一个唯一的名称,我使用"photo-input“并使用它。所以JS是:
$(document).on('change', '.photo-input', function(){
alert("this.id: " + this.id);
readURL(this, this.id);
});
function readURL(input, id) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#campImage'+id).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
因此,您会注意到,我将id设置为每个选项卡的唯一值。然后,我将该值附加到我想要填充的输入id中(图片不是这个表单中唯一的一个,我尽量保持简单)。
https://stackoverflow.com/questions/51567276
复制相似问题