Javascript 如何重置(清除)文件输入

Javascript 如何重置(清除)文件输入,javascript,internet-explorer,cross-browser,file-io,Javascript,Internet Explorer,Cross Browser,File Io,如何在IE中重置文件输入,我使用了以下方法,它在chrome和FF中工作,但在IE中不工作 fileInputElement.value=”“ IE中的替代方案是什么?如果fileInputElement以fileInputForm的形式单独存在,您可以执行以下操作: window.fileInputForm.reset(); 否则,对于IE,您必须用克隆替换元素: fileInputElement.parentNode.replaceChild( fileInputElement.c

如何在IE中重置文件输入,我使用了以下方法,它在chrome和FF中工作,但在IE中不工作

fileInputElement.value=”“


IE中的替代方案是什么?

如果
fileInputElement
fileInputForm
的形式单独存在,您可以执行以下操作:

window.fileInputForm.reset();
否则,对于IE,您必须用克隆替换元素:

fileInputElement.parentNode.replaceChild(
    fileInputElement.cloneNode(true), 
    fileInputElement
);

您无法自行重置文件输入。您可以做的是将文件输入包装在
标记中,然后重置表单。使用jQuery,您可以执行
$('#form_id')[0].reset()document.getElementById('form_id').reset()

解决方案 以下代码适用于我的jQuery。它可以在每个浏览器中工作,并允许保留事件和自定义属性

var $el = $(fileInputElement);
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();
var$el=$(fileInputElement);
$el.wrap(“”).closest('form').get(0.reset();
$el.unwrap();
演示 有关代码和演示,请参阅

链接

由@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);
  }

}

通过IE 10我解决了以下问题:

    var file = document.getElementById("file-input");
    file.removeAttribute('value');
    file.parentNode.replaceChild(file.cloneNode(true),file);
其中:

<input accept="image/*" onchange="angular.element(this).scope().uploadFile(this)" id="file-input" type="file"/>


IE的代码确实可以重置,但它丢失了所有事件:(使用延迟事件处理程序以避免这种情况发生(例如jQuery.on处理程序)。IE10为我提供了一个很好的简单解决方案。知道document.getElementById('form_id').reset()工作的原因吗,document.getElementById('form_id')[0]。reset()不工作,以及jQuery为什么需要[0]?(顺便说一句,你至少为我节省了30分钟)
getElementById()
不返回数组,因此结果中没有索引
[0]
。jQuery确实返回一个对象数组,因此当您指定
[0]
时,您将检索返回集中的第一个元素。非常感谢!我已经尝试了许多解决方案。大多数都不起作用。下面是一个有效的方法。--仅用3行。