jQuery如何在动态加载的选项卡中显示选定的图像(目前仅适用于第一个选项卡)



我正在动态创建选项卡,并且在每个选项卡上都显示一个图像。然后我允许选择一个新图像来替换它。当在第一个选项卡上选择新图像时,它就会显示出来(显示的原始图像会被替换(。但是,在随后的选项卡上,原始图像不会被替换(显示新的图像名称(。控制台中没有错误。

因此,在我的研究中,我找到了解决方案"$(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>';

答案是使每个"id="都是唯一的。在这种情况下,id="photo"需要更改为"id="'+obj.eventId+'"'和"id="campImage"更改为"id="campImage'+obj.eventId+'"。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"每次都会改变,我该如何识别它已经改变了?在课堂上添加一个唯一的名字,我使用"照片输入"并使用它。因此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中(图片不是这个表单中唯一的一个,我保持了简单(。

最新更新