上传图像并使用JQuery将其附加到正文

时间:2016-06-10 09:43:08

标签: javascript jquery html image

我正在尝试创建一个网站构建器,其中我们可以选择添加HTML元素 喜欢文字,图片,视频等 为了通过设备上传图像,我使用了

$(document).ready(function() {

  $("#addImage").click(function() {
    $("#fileinput").click();
  });

  $("#fileinput").click(function() {
    $("#fileinput").change(function() {
      if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = imageIsLoaded;
        reader.readAsDataURL(this.files[0]);
      }
    });
  });

  var x=0;
  function imageIsLoaded(e) {
    var picture = '<img src="' + e.target.result + '" style="width:200px;height:200px;" class="' + x + 'thImage">'
    $("body").append(picture);
    x=x+1;
  }

});
<!doctype html>
<html>

<body>
  <input type="file" id="fileinput" style="height:0;overflow:hidden;">
  <button id="addImage">Upload image</button>
</body>

</html>
 我将该功能链接到另一个按钮并隐藏了实际的文件输入按钮,使其看起来很好。

这只是第一次正常。第n次添加图像时,图像将被添加n次。

此外,由于我正在添加图像,因此我需要一个替换版本(),因为我可能想要一次又一次地添加相同的图像。

帮我解决这个问题。谢谢。

1 个答案:

答案 0 :(得分:1)

重复图像的问题是因为您要分配新图像  每次连续点击都会有change个事件处理程序。因此,第N次单击时,会附加N个图像。您只需要从change事件中解开click()事件处理程序。

此外,要删除上一张图像,您可以在添加下一张图像之前将图像附加到容器和empty()该容器,如下所示:

&#13;
&#13;
$(document).ready(function() {
  $("#addImage").click(function() {
    $("#fileinput").click();
  });

  $("#fileinput").change(function() {
    if (this.files && this.files[0]) {
      var reader = new FileReader();
      reader.onload = imageIsLoaded;
      reader.readAsDataURL(this.files[0]);
    }
  });

  function imageIsLoaded(e) {
    var x = 'foo';
    var picture = '<img src="' + e.target.result + '" style="width:200px;height:200px;" class="' + x + 'thImage">'
    $(".preview").empty().append(picture);
  }

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="fileinput" style="height:0;overflow:hidden;">
<button id="addImage">Upload image</button>

<div class="preview"></div>
&#13;
&#13;
&#13;

请注意,原始样本中未定义x。我认为这只是你的问题所遗漏的,所以只需添加一个占位符变量foo作为值。