问题描述:

I am not javascript or html expert. I know very basic.

Here is my code which I click on image open file chooser and I choose new image and this append it to previous image. This works fine but I need to replace the image with previous one instead of appending. Appreciate if any one can tweak it as I'm not sure how to do it:

<div id="current-user"></div>

<br>

<input type="file" id="choose" multiple src="/logo.png" />

<script>

function readImage(file) {

var reader = new FileReader();

var image = new Image();

reader.readAsDataURL(file);

reader.onload = function(_file) {

image.src = _file.target.result; // url.createObjectURL(file);

image.onload = function() {

var w = this.width,

h = this.height,

t = file.type, // ext only: // file.type.split('/')[1],

n = file.name,

s = ~~(file.size/1024) +'KB';

$('#uploadPreview').append('<img src="'+ this.src +'"> '+w+'x'+h+' '+s+' '+t+' '+n+'<br>');

};

image.onerror= function() {

alert('Invalid file type: '+ file.type);

};

};

}

$("#choose").change(function (e) {

if(this.disabled) return alert('File upload not supported!');

var F = this.files;

if(F && F[0]) for(var i=0; i<F.length; i++) readImage( F[i] );

});

</script>

Edit:

I could handle my page to bring an image and append it to previous image. But I need to remove the previous image and add a new image. I used to method of replaceWith() and replcaAll() but they didn't work.

网友答案:

Instead of:

$('#uploadPreview').append(...

Use:

$('#uploadPreview').html(...

Using html() method replaces all inner HMTL content from #uploadPreview element

网友答案:

You may change the src attribute of your img element, that's easy way in my opinion:

    var img = document.getElementById("idOfImage");
    img.attributes.src.value = "2.jpg";           //URL of other image

And in this way you can also change the values of other attributes.

网友答案:

Don't empty the parent:

$('#uploadPreview').empty(); //don't use this

Just do:

$('#uploadPreview').find("img").attr("src",this.src); //then you don't need to set height and width again

Or follow this snippet:

$("#image").on("click", function() {
  $(this).attr("src", "http://sd.keepcalm-o-matic.co.uk/i/keep-calm-its-already-done.png")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <img id="image" src="http://i.imgur.com/W3FNHHH.png" height=200 width=200>


</div>
网友答案:

I am actually adding following line before appending image:

$('#uploadPreview').empty();

相关阅读:
Top