已实现图片上传预览,点击清除按钮无法移除预览求助
Hey there, let's work through why your image preview isn't clearing properly!
First off, I spotted a typo in the code you tried: removeAtr should be removeAttr—that's one easy fix. But even correcting that, we need a couple extra steps to fully reset both the preview and the file input's state. Here's how to get it working:
1. Correct the Typo & Update the Preview Image
If your preview element is an <img> with the ID files, fixing the method name and setting the src to an empty string (instead of just removing the attribute) will work more reliably across browsers:
// Clear the preview image (most consistent approach) $('#files').attr('src', ''); // Alternatively, if you prefer using removeAttr // $('#files').removeAttr('src');
2. Reset the File Input Control
Just clearing the preview image isn't enough—your file input still holds a reference to the selected file. Resetting it will fully reset the input's state:
// Replace 'fileInput' with your actual file input's ID $('#fileInput').val(''); // Then clear the preview as above $('#files').attr('src', '');
3. Integrate This Into Your Form Reset Function
The native form reset() method only resets form controls to their default values—it doesn't touch dynamically added content like your image preview. Update your reset function to include the preview-clearing step:
function resetYourForm() { // Run the native form reset first document.getElementById('yourFormId').reset(); // Now clear the image preview $('#files').attr('src', ''); // If you have multiple previews in a container, empty the container instead: // $('#previewContainer').empty(); }
Quick Debugging Checks
- Open your browser's dev tools (F12), go to the Console tab, and run
$('#files').attr('src', '')directly. If the preview clears, the issue might be that your clear button's click event isn't binding correctly. - Double-check that your preview image's ID is actually
files—no typos, no duplicate IDs on the page.
That should get your clear button working as expected!
内容的提问来源于stack exchange,提问作者Roberto Flores

