是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:

$('#control').attr({ value: '' }); 

但这并不奏效。


当前回答

我的火狐40.0.3只支持这个功能

 $('input[type=file]').val('');
 $('input[type=file]').replaceWith($('input[type=file]').clone(true));

其他回答

.clone()东西在Opera(可能还有其他)中不起作用。它保存内容。

对我来说,这里最接近的方法是Jonathan之前的方法,但是确保字段保留其名称、类等,在我的例子中导致了混乱的代码。

像这样的东西可能很管用(也要感谢昆汀):

function clearInput($source) {
    var $form = $('<form>')
    var $targ = $source.clone().appendTo($form)
    $form[0].reset()
    $source.replaceWith($targ)
}

什么? 在验证函数中

document.onlyform.upload.value="";

假设upload是名称:

<input type="file" name="upload" id="csv_doc"/>

我使用JSP,不确定这是否有区别…

对我来说是可行的,而且我觉得这样简单多了。

function clear() {
    var input = document.createElement("input");
    input.setAttribute('type', 'file');
    input.setAttribute('value', '');
    input.setAttribute('id', 'email_attach');

    $('#email_attach').replaceWith( input.cloneNode() );
}

简单:将<form>环绕在元素周围,在表单上调用reset,然后使用.unwrap()删除表单。与此线程中的.clone()解决方案不同,在结束时您将得到相同的元素(包括在其上设置的自定义属性)。

测试和工作在Opera, Firefox, Safari, Chrome和IE6+。也适用于其他类型的表单元素,除了type="hidden"。

窗口。重置=函数(e) { e.wrap .closest(“< >形式”)(“形式”). get (0) .reset (); e.unwrap (); } < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> < >形式 <input id="file" type="file"> < br > <input id="text" type="text" value="Original"> > < /形式 <按钮onclick = "重置($(' #文件'))“>重置文件> < /按钮 <按钮onclick = "重置($(' #文本'))“>重置文本> < /按钮

JSFiddle

正如Timo在下面指出的那样,如果您有按钮来触发<表单>内部字段的重置,那么您必须在事件上调用. preventdefault()来防止<按钮>触发提交。


EDIT

由于一个未修复的错误,无法在ie11中工作。输入中的文本(文件名)被清除,但其file列表仍然填充。

最后我得出了这个结论:

if($.browser.msie || $.browser.webkit){
  // doesn't work with opera and FF
  $(this).after($(this).clone(true)).remove();  
}else{
  this.setAttribute('type', 'text');
  this.setAttribute('type', 'file'); 
}

也许不是最优雅的解决方案,但据我所知它很有效。