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

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

但这并不奏效。


当前回答

在IE8中,为了安全起见,他们将文件上传字段设置为只读。查看IE团队的博客文章:

Historically, the HTML File Upload Control () has been the source of a significant number of information disclosure vulnerabilities. To resolve these issues, two changes were made to the behavior of the control. To block attacks that rely on “stealing” keystrokes to surreptitiously trick the user into typing a local file path into the control, the File Path edit box is now read-only. The user must explicitly select a file for upload using the File Browse dialog. Additionally, the “Include local directory path when uploading files” URLAction has been set to "Disable" for the Internet Zone. This change prevents leakage of potentially sensitive local file-system information to the Internet. For instance, rather than submitting the full path C:\users\ericlaw\documents\secret\image.png, Internet Explorer 8 will now submit only the filename image.png.

其他回答

简单回答:换掉它。

在下面的代码中,我使用replaceWith jQuery方法将控件替换为其本身的克隆。如果您将任何处理程序绑定到此控件上的事件,我们也希望保留这些处理程序。为此,我们传入true作为clone方法的第一个参数。

<input type="file" id="control"/>
<button id="clear">Clear</button>
var control = $("#control");

$("#clear").on("click", function () {
    control.replaceWith( control = control.clone( true ) );
});

小提琴:http://jsfiddle.net/jonathansampson/dAQVM/

如果克隆,同时保留事件处理程序,提出了任何问题,您可以考虑使用事件委托来处理父元素对该控件的单击:

$("form").on("focus", "#control", doStuff);

这可以防止在刷新控件时将任何处理程序与元素一起克隆。

这对我很有用。

$("#file").replaceWith($("#file").clone());

http://forum.jquery.com/topic/how-to-clear-a-file-input-in-ie

希望能有所帮助。

它适用于所有浏览器。

        var input = $(this);
        var next = this.nextSibling;
        var parent = input.parent();
        var form = $("<form></form>");
        form.append(input);
        form[0].reset();
        if (next) {
            $(next).before(input);
        } else {
            parent.append(input);
        }

我能够得到我的工作与以下代码:

var input = $("#control");    
input.replaceWith(input.val('').clone(true));

出于明显的安全原因,您不能设置文件输入的值,甚至是空字符串。

你所要做的就是重置字段所在的表单,或者如果你只想重置包含其他字段的表单的文件输入,使用这个:

function reset_field (e) {
    e.wrap('<form>').parent('form').trigger('reset');
    e.unwrap();
}​

这里有一个例子:http://jsfiddle.net/v2SZJ/1/