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

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

但这并不奏效。


当前回答

将其设置为异步的,并在完成按钮所需的操作后重置它。

    <!-- Html Markup --->
    <input id="btn" type="file" value="Button" onchange="function()" />

    <script>
    //Function
    function function(e) {

        //input your coding here           

        //Reset
        var controlInput = $("#btn");
        controlInput.replaceWith(controlInput = controlInput.val('').clone(true));
    } 
    </script>

其他回答

你可以像这样用它的克隆来替换它

var clone = $('#control').clone();

$('#control').replacewith(clone);

但这个克隆与它的价值太,所以你最好喜欢这样

var emtyValue = $('#control').val('');
var clone = emptyValue.clone();

$('#control').replacewith(clone);

我一直在寻找简单而干净的方法来清除HTML文件输入,上面的答案是伟大的,但没有一个真正回答我在寻找什么,直到我在网络上遇到了一个简单而优雅的方法来做到这一点:

var $input = $("#control");

$input.replaceWith($input.val('').clone(true));

这一切都要归功于克里斯·科伊尔。

// Referneces var control = $("#control"), clearBn = $("#clear"); // Setup the clear functionality clearBn.on("click", function(){ control.replaceWith( control.val('').clone( true ) ); }); // Some bound handlers to preserve when cloning control.on({ change: function(){ console.log( "Changed" ) }, focus: function(){ console.log( "Focus" ) } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" id="control"> <br><br> <a href="#" id="clear">Clear</a>

我被这里的选项困住了。下面是我做的一个有效的方法:

<form>
 <input type="file">
 <button type="reset" id="file_reset" style="display:none">
</form>

你可以使用jQuery来触发重置,代码如下:

$('#file_reset').trigger('click');

(JSFIDDLE: http://jsfiddle.net/eCbd6/)

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

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

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