Javascript 如何重置(清除)文件输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/9011644/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to reset (clear) file input
提问by Sami Al-Subhi
how can I reset file input in IE, I used the following and it worked in chrome and FF but not IE
如何在 IE 中重置文件输入,我使用了以下内容,它在 chrome 和 FF 中有效,但在 IE 中无效
fileInputElement.value=""
fileInputElement.value=""
what's the alternative in IE ?
IE 中的替代方案是什么?
回答by mVChr
If fileInputElementis on its own in the form fileInputForm, you can do:
如果fileInputElement在表单中单独存在fileInputForm,您可以执行以下操作:
window.fileInputForm.reset();
Otherwise for IE you'll have to replace the element with a clone:
否则,对于 IE,您必须用克隆替换元素:
fileInputElement.parentNode.replaceChild(
    fileInputElement.cloneNode(true), 
    fileInputElement
);
回答by Gyrocode.com
SOLUTION
解决方案
The following code worked for me with jQuery. It works in every browser and allows to preserve events and custom properties.
以下代码适用于 jQuery。它适用于每个浏览器,并允许保留事件和自定义属性。
var $el = $(fileInputElement);
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();
DEMO
演示
See this jsFiddlefor code and demonstration.
有关代码和演示,请参阅此 jsFiddle。
LINKS
链接
回答by Frank Adler
Cross-Browser solution by @Gyrocode.com in vanilla JS:
@Gyrocode.com 在 vanilla JS 中的跨浏览器解决方案:
var clearFileInput = function (input) {
  if (!input) {
    return;
  }
  // standard way - works for IE 11+, Chrome, Firefox, webkit Opera
  input.value = null;
  if (input.files && input.files.length && input.parentNode) {
    // workaround for IE 10 and lower, pre-webkit Opera
    var form = document.createElement('form');
    input.parentNode.insertBefore(form, input);
    form.appendChild(input);
    form.reset();
    form.parentNode.insertBefore(input, form);
    input.parentNode.removeChild(form);
  }
}
回答by Gavin
You can't reset the File input by itself. What you can do is wrap your File input in a <form id="form_id">tag and reset the form. With jQuery you can do $('#form_id')[0].reset();and in JavaScript you can do document.getElementById('form_id').reset().
您无法自行重置 File 输入。您可以做的是将您的 File 输入包装在一个<form id="form_id">标签中并重置表单。使用 jQuery 可以做到,$('#form_id')[0].reset();而在 JavaScript 中则可以做到document.getElementById('form_id').reset()。
回答by Alvaro Joao
With IE 10I resolved the problem with :
使用IE 10我解决了这个问题:
    var file = document.getElementById("file-input");
    file.removeAttribute('value');
    file.parentNode.replaceChild(file.cloneNode(true),file);
where :
在哪里 :
<input accept="image/*" onchange="angular.element(this).scope().uploadFile(this)" id="file-input" type="file"/>

