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

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

但这并不奏效。


当前回答

它适用于所有浏览器。

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

其他回答

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

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

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

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

在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.

一个简单的方法是改变输入类型,然后再把它改回来。

就像这样:

var input = $('#attachments');
input.prop('type', 'text');
input.prop('type', 'file')

这很简单lol(适用于所有浏览器[除了opera]):

$('input[type=file]').each(function(){
    $(this).after($(this).clone(true)).remove();
});

JS Fiddle: http://jsfiddle.net/cw84x/1/

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

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