通过 JavaScript 清除 HTML 文件上传字段 [英] Clearing an HTML file upload field via JavaScript
问题描述
我想在用户选择另一个选项时重置文件上传字段.
I want to reset a file upload field when the user selects another option.
这可以通过 JavaScript 实现吗?我怀疑文件上传元素被区别对待,因为它与用户的文件系统交互,而且它可能是不可变的.
Is this possible via JavaScript? I'm suspecting that the file upload element is treated differently because it interacts with the user's file system, and maybe it's immutable.
基本上,我想要的是(伪代码):
Basically, what I want is something like (pseudo-code):
// Choose selecting existing file
$('#select-file').bind('focus', function() {
// Clear any files currently selected in #upload-file
$('#upload-file').val('');
}) ;
// Choose uploading new one - this works ok
$('#upload-file').bind('focus', function() {
// Clear any files currently selected in #select-file
$('#select-file').val('');
}) ;
注意:这个问题及其答案涵盖了从 2009 年到今天的这段时间.浏览器和方法在那个时期发生了变化,请考虑到这一点来选择您的解决方案:)
NB: This question and its answers span the period from 2009 to today. Browsers and approaches have changed in that time, please select your solutions with this in mind :)
推荐答案
你不能在大多数浏览器中设置输入值,但你可以做的是创建一个新元素,从旧元素复制属性,然后交换两个.
You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.
给定一个表格:
<form>
<input id="fileInput" name="fileInput" type="file" />
</form>
直接的 DOM 方式:
The straight DOM way:
function clearFileInput(id)
{
var oldInput = document.getElementById(id);
var newInput = document.createElement("input");
newInput.type = "file";
newInput.id = oldInput.id;
newInput.name = oldInput.name;
newInput.className = oldInput.className;
newInput.style.cssText = oldInput.style.cssText;
// TODO: copy any other relevant attributes
oldInput.parentNode.replaceChild(newInput, oldInput);
}
clearFileInput("fileInput");
简单的DOM方式.这可能不适用于不喜欢文件输入的旧浏览器:
Simple DOM way. This may not work in older browsers that don't like file inputs:
oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);
jQuery 方式:
$("#fileInput").replaceWith($("#fileInput").val('').clone(true));
// .val('') required for FF compatibility as per @nmit026
通过 jQuery 重置整个表单:https://stackoverflow.com/a/13351234/1091947
Resetting the whole form via jQuery: https://stackoverflow.com/a/13351234/1091947
这篇关于通过 JavaScript 清除 HTML 文件上传字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!