首页 > 解决方案 > 使用动态创建的内容清除 Div 的问题

问题描述

我遇到以下问题。我有一个表单,其中包含一个允许选择图像的按钮。选择图像时,脚本会显示图像的尺寸以及拇指指甲。问题是,如果用户选择另一个图像,尺寸会显示两次。目前尺寸重复。我该如何防止这种情况。

请参阅我的代码中标记为“THE LINE BELOW”的以下行

window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("browse2"),
  elPreview = document.getElementById("preview6"),
  elPreviewtext = document.getElementById("previewtext6"),
  useBlob = false && window.URL;

function readImage(file) {
  console.log("elPreviewtext", elPreviewtext);
  var reader = new FileReader();
  reader.addEventListener("load", function() {
    var image = new Image();
    image.addEventListener("load", function() {
      var imageInfo = file.name;
      var filetype = imageInfo;
      var ext = filetype.split('.').pop();
      if (image.width != editw && image.height != edith) {
        $.alert({
          title: 'Image select error!',
          content: 'The image you have seleted is incorrect, ' + image.width + ' by ' + image.height + ' portrate.<br/><br/> "Please resize your image to the correct size in landscape.<br/><br/>Resizing upwards reduces the quality of the image. Start with a large image and resize downwards.',
          animation: 'zoom',
          boxWidth: '50%',
          closeAnimation: 'zoom',
          buttons: {
            okay: {
              text: 'Try again',
              btnClass: 'btn-blue'
            }
          }
        });
      } else {
        var imageInfotext = '';
        var imageInfotext = 'Display width: ' + image.width + ',<br/>Display height: ' + image.height;
elPreviewtext.innerHtml = "";        
elPreview.appendChild(this);
        // THE LINE BELOW DISPLAYS THE IMAGE DIMENTION IN A DIV ON THE FORM "<div class="bodytext" id="previewtext6"></div>"
        elPreviewtext.insertAdjacentHTML("beforeend", imageInfotext + '<br>');
        if (useBlob) {
          window.URL.revokeObjectURL(image.src);
        }
      }
    });
    image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
  });
  reader.readAsDataURL(file);
}

非常感谢您的帮助和时间。

标签: jquery

解决方案


只需在添加信息之前清除元素(只需添加一些代码行):

var imageInfotext = '';
var imageInfotext = 'Display width: ' + image.width + ',<br/>Display height: ' + image.height;
elPreview.appendChild(this);
// HERE CLEAR THE CONTENT
elPreviewtext.innerHtml = "";
// THE LINE BELOW DISPLAYS THE IMAGE DIMENTION IN A DIV ON THE FORM "<div class="bodytext" id="previewtext6"></div>"
elPreviewtext.insertAdjacentHTML("beforeend", imageInfotext + '<br>');

推荐阅读