用于删除图片的{Javascript代码

时间:2015-04-22 12:58:59

标签: javascript html

我想点击"删除图片"链接,它删除图像。请帮帮我。

   

<script>
function previewFile(){

   var preview = document.querySelector('img'); 
   var file    = document.querySelector('input[type=file]').files[0];
   var reader  = new FileReader();

   reader.onloadend = function () {
       preview.src = reader.result;
   }
   if (file) {
       reader.readAsDataURL(file); 
   } else {
       preview.src = "";
   }
}

  previewFile();  

</script>

<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
<a href="#">remove image </a>

  </body>
</html>

4 个答案:

答案 0 :(得分:1)

<img id='image' src="" height="200" alt="Image preview...">
<a id='remove' href="#">remove image </a>

<script>
$(function rmv() {
    $('#remove').click(function() {
            $('#image').remove();
        }

}); 
</script>

答案 1 :(得分:1)

如果您无法将id属性添加到img,则可以使用原始javascript将其删除 - 它假定图像直接位于锚标记之前,只允许它们之间的一个文本节点:

function removeImage(el){
    if(!el.previousSibling.tagName){//if it is textnode like newline etc. we go one back 
        var el = el.previousSibling;
    }
    if(el.previousSibling.tagName && el.previousSibling.tagName=='IMG'){
        el.previousSibling.remove();
    }
}

<img src="" height="200" alt="Image preview...">
<a href="#" onclick="removeImage(this);">remove image</a>

答案 2 :(得分:0)

将img元素保留在div中并为此元素分配id

   <input type="file" onchange="previewFile()"><br>
<div id="imgDiv">    <img id="image1" src="" height="200" alt="Image preview..."></div>
    <a href="#">remove image </a>

      </body>
    </html>

<script>
function previewFile() {

  var d = document.getElementById('imgDiv');

  var olddiv = document.getElementById("image1");

  d.removeChild(olddiv);

}

</script>

答案 3 :(得分:0)

<img src="" id="image" height="200" alt="Image preview...">
<a href="#" onclick="foo()">remove image </a>

JS:

function foo(){
    var image =  document.getElementById("image");
     if (image != null)
     {
          image.parentNode.removeChild(image);
     }
}