猿问

在输入单击/更改时隐藏图像预览

我在 JavaScript 中创建了一个图像预览,其中包含一些我在这里找到的脚本,我是 JS 新手,现在我正在尝试替换内容而不是附加内容。这是代码


我试过像其他类似的问题一样在 SO 上放置empty(), replaceWith(), remove(), 之前appendTo(),我尝试创建一个函数来隐藏 div,但似乎没有任何效果。我想知道是否有人会知道为什么这些功能不起作用,我做错了什么吗?


//my html/php


echo '<input required type="file" name="filesToUpload[]" multiple 

id="image_upload" accept=".jpg, .jpeg">';

echo '<div id="gallery-preview" class="gallery-preview"></div>';


//javascript

    $(function() {


        var imagesPreview = function(input, placeToInsertImagePreview) {


            if (input.files) {


                var filesAmount = input.files.length;


                for (i = 0; i < filesAmount; i++) {


                    var reader = new FileReader();


                    reader.onload = function(event) {


                        $($.parseHTML('<img style="width:150px; height:75px; margin-left:2px; margin-right:2px; border:1px solid black; padding:2px;">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);

                    }

                    reader.readAsDataURL(input.files[i]);

                }

            }

        };

        $('#image_upload').on('change', function() {

            imagesPreview(this, 'div.gallery-preview');

        });

    });

当我hide()为 div创建一个函数时gallery-preview,预览不再起作用。与上述其他功能相同


万千封印
浏览 87回答 1
1回答

蛊毒传说

我认为您每次运行该功能时都试图将其设置为空。将代码中的更改功能修改为以下内容&nbsp;$('#image_upload').on('change', function() {&nbsp; &nbsp; &nbsp; &nbsp; //this line will set the contents to empty before you run your function&nbsp; &nbsp; &nbsp; &nbsp; $('div.gallery-preview').html('');&nbsp; &nbsp; &nbsp; &nbsp; //now call your function&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; imagesPreview(this, 'div.gallery-preview');&nbsp;});
随时随地看视频慕课网APP
我要回答