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

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

但这并不奏效。


当前回答

我使用了https://github.com/malsup/form/blob/master/jquery.form.js,它有一个名为clearInputs()的函数,它是跨浏览器的,经过良好测试,易于使用,并在需要时处理IE问题和隐藏字段清除。也许这个解决方案有点长,只清除文件输入,但如果你正在处理跨浏览器的文件上传,那么这个解决方案是推荐的。

用法简单:

// Clear all file fields:
$("input:file").clearInputs();

// Clear also hidden fields:
$("input:file").clearInputs(true);

// Clear specific fields:
$("#myfilefield1,#myfilefield2").clearInputs();
/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
    var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (re.test(t) || tag == 'textarea') {
            this.value = '';
        }
        else if (t == 'checkbox' || t == 'radio') {
            this.checked = false;
        }
        else if (tag == 'select') {
            this.selectedIndex = -1;
        }
        else if (t == "file") {
            if (/MSIE/.test(navigator.userAgent)) {
                $(this).replaceWith($(this).clone(true));
            } else {
                $(this).val('');
            }
        }
        else if (includeHidden) {
            // includeHidden can be the value true, or it can be a selector string
            // indicating a special test; for example:
            //  $('#myForm').clearForm('.special:hidden')
            // the above would clean hidden inputs that have the class of 'special'
            if ( (includeHidden === true && /hidden/.test(t)) ||
                 (typeof includeHidden == 'string' && $(this).is(includeHidden)) )
                this.value = '';
        }
    });
};

其他回答

文件输入的值是只读的(出于安全原因)。不能通过编程方式使其变为空白(除非调用表单的reset()方法,该方法的范围比该字段更广)。

简单:将<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列表仍然填充。

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

这对我不起作用:

$('#Attachment').replaceWith($(this).clone());
or 
$('#Attachment').replaceWith($('#Attachment').clone());

所以在asp mvc中,我使用razor功能替换文件输入。 首先创建一个变量为输入字符串Id和名称,然后使用它显示在页面和重置按钮点击替换:

@{
    var attachmentInput = Html.TextBoxFor(c => c.Attachment, new { type = "file" });
}

@attachmentInput

<button type="button" onclick="$('#@(Html.IdFor(p => p.Attachment))').replaceWith('@(attachmentInput)');">--</button>

简单回答:换掉它。

在下面的代码中,我使用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);

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