多图预览问题咨询:切换文件时旧预览未清除的解决方法
Hey there! I see the issue you're facing—when you select new images, the old previews stick around and new ones get appended on top, even though only the new files are actually uploaded. Let's fix that right away.
The Root Cause
Your current code doesn't clear out existing preview content before adding new images. Every time you select files, it just adds to the #previewHolder div instead of starting fresh. That's why you end up with duplicate previews.
Modified JavaScript Code
Here's the fixed version of your script, with key changes explained below:
$(function() { // Multiple images preview in browser var imagesPreview = function(input, placeToInsertImagePreview) { // Step 1: Clear all old previews before adding new ones $(placeToInsertImagePreview).empty(); if (input.files) { var filesAmount = input.files.length; // Use let for loop variable to avoid scope issues in the reader callback for (let i = 0; i < filesAmount; i++) { var reader = new FileReader(); var currentFile = input.files[i]; // Store file to access its details later reader.onload = function(event) { $('<div class="previewdeleter position-relative" style="height:200px;width: 200px; display: inline-block; position: relative !important;">' + '<img alt="' + currentFile.name + '" src=' + event.target.result + ' style="height:200px;width: 100%; display: inline-block;">' + '</div>') .appendTo(placeToInsertImagePreview); } reader.readAsDataURL(currentFile); } } }; $('#images').on('change', function() { imagesPreview(this, '#previewHolder'); }); });
Key Changes Made:
- Clear Existing Previews: Added
$(placeToInsertImagePreview).empty()at the start of the function. This wipes out all old preview elements immediately when new files are selected, ensuring only the latest images are shown. - Removed Broken Logic: Deleted the invalid
if ('.previewdeleter' ===('image') )block—this line had incorrect syntax and no meaningful role in your preview flow. - Fixed Scope Issues: Used
letfor the loop variablei(instead ofvar) so each reader callback references the correct file. We also stored the current file in a variable to add a meaningfulaltattribute using the file name. - Cleaned Up Syntax: Removed the extra comma in
reader.readAsDataURL(input.files[i],);to avoid potential runtime errors.
Updated HTML (Optional Tweaks)
Your HTML works, but we can remove some unnecessary attributes for clarity:
<input value="" type="file" id="images" name="images[]" accept="image/*" multiple /> <div id="previewHolder" class="position-relative"> </div>
- Removed the
multipleattribute from#previewHolder(it only applies to input elements). - Removed the invalid
data-item-id-div="input.files[i].length"attribute—this static value wouldn't resolve to anything useful. If you need to track file identifiers, you can add dynamic values in the JavaScript instead.
Now when you select new images, the old previews will be cleared automatically, and only the new ones will appear in the preview area!
内容的提问来源于stack exchange,提问作者Dimi

