在用户选择要上传的文件后,我已修改当前表单以触发表单提交。上传完成后,我致电:
$('#file').val('');
重置文件输入字段。
HTML
<input name="file" type="file" id="file"/>
这适用于Chrome,FF和Safari,但在IE中不起作用。是否有针对IE的解决方法或更好的解决方案?
答案 0 :(得分:6)
您无法更改文件输入类型的值,因为这会引入安全漏洞。相反,只需用新的文件输入替换文件输入。而不是$('#file').val('')
,请执行以下操作:
$('#file').replaceWith('<input name="file" type="file" id="file"/>');
更好的方法是克隆原始版本的副本并将其存储在内存中。当您需要替换它时,只需使用克隆的副本,然后再次克隆它。所以,像这样:
$(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());
});
})
请注意,我正在使用jQuery.on()的委托版本,因此该事件在替换后仍可用于新输入。