为什么IE不重置文件输入字段?

Pau*_*aul 4 html jquery file-upload

在用户选择要上传的文件后,我已修改当前表单以触发表单提交.上传完成后,我致电:

$('#file').val('');
Run Code Online (Sandbox Code Playgroud)

重置文件输入字段.

HTML
<input name="file" type="file" id="file"/>
Run Code Online (Sandbox Code Playgroud)

这适用于Chrome,FF和Safari,但在IE中不起作用.IE是否有解决方法或更好的解决方案?

Ben*_*Lee 6

您无法更改文件输入类型的值,因为这会引入安全漏洞.相反,只需用新的文件输入替换文件输入.而不是$('#file').val(''),这样做:

$('#file').replaceWith('<input name="file" type="file" id="file"/>');
Run Code Online (Sandbox Code Playgroud)

更好的方法是克隆原始版本的副本并将其存储在内存中.当您需要替换它时,只需使用克隆的副本,然后再次克隆它.所以,像这样:

$(document).ready(function() {
    var empty_input = $('#file').clone();

    $('#the-form').on('change', '#file', function(el) {
        $('#the-form').submit(); // assuming the target is a hidden iframe
        $(this).replaceWith(empty_input.clone());
    });
})
Run Code Online (Sandbox Code Playgroud)

请注意,我正在使用jQuery.on()的委托版本,因此事件在替换后仍然可以在新输入上使用.