简体   繁体   中英

How can I delete image uploaded?

My html code is like this :

<input type='file' multiple/>
<?php
    for($i=0;$i<5; $i++) {
?>
    <div class="img-container" id="box<?php echo $i ?>">
        <button  style="display: none;" type="submit" class="btn btn-danger show-button">
            <i class="glyphicon glyphicon-trash"></i>
        </button>
    </div>
<?php
    }
?>

My javascript code is like this :

    $(function () {
        $(":file").change(function () {
            var noOfFiles = this.files.length;
            for(var i=0; i < noOfFiles; i++) {        
                var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[i]);
            }        
        });
    });

    function imageIsLoaded(e) {
        var imgTmpl = '<img height="142" width="162" src='+e.target.result+'>';
        var IsImgAdded=false;
        $('.img-container').each(function(){
            if($(this).find('img').length==0 && IsImgAdded==false){
                $(this).append(imgTmpl);
                IsImgAdded=true;
                $(this).find('.show-button').show();
            }
        });     
    };

    $(".show-button").click(function(){
        $(this).find('img').hide()
    });

Demo and full code is like this : http://phpfiddle.org/main/code/uu9x-w50q

I try use hide the image. But it does not work

How can I solve this problem?

You should use parent method in order to achieve this, because image DOM element belongs to the parent of .show-button .

$(document).on('click',".show-button",function(){
    var imgTmpl = '<div class="img-container">'+
               '<button  style="display: none;" type="submit" class="btn btn-danger show-button">'+
               '<i class="glyphicon glyphicon-trash"></i>'+
                '</button></div>';
    $(this).parent().remove();
    $('body').append(imgTmpl);
});

Here is solution.

Try with closest()

 $(".show-button").click(function(){
        $(this).closest('.img-container').find('img').hide()
        //$(this).closest('.img-container').children().remove() used for remove the all child element of the `.img-container`
        console.log('hi')
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM