是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:
$('#control').attr({ value: '' });
但这并不奏效。
是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:
$('#control').attr({ value: '' });
但这并不奏效。
当前回答
我被这里的选项困住了。下面是我做的一个有效的方法:
<form>
<input type="file">
<button type="reset" id="file_reset" style="display:none">
</form>
你可以使用jQuery来触发重置,代码如下:
$('#file_reset').trigger('click');
(JSFIDDLE: http://jsfiddle.net/eCbd6/)
其他回答
$("#control").val(")就是你所需要的!使用JQuery 1.11在Chrome上测试
其他用户也在Firefox中进行了测试。
我的火狐40.0.3只支持这个功能
$('input[type=file]').val('');
$('input[type=file]').replaceWith($('input[type=file]').clone(true));
我尝试了用户提到的大多数技术,但没有一种在所有浏览器中都有效。即:克隆()不工作在FF文件输入。 我最终手动复制文件输入,然后用复制的文件替换原始文件。它适用于所有浏览器。
<input type="file" id="fileID" class="aClass" name="aName"/>
var $fileInput=$("#fileID");
var $fileCopy=$("<input type='file' class='"+$fileInput.attr("class")+" id='fileID' name='"+$fileInput.attr("name")+"'/>");
$fileInput.replaceWith($fileCopy);
简单回答:换掉它。
在下面的代码中,我使用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);
这可以防止在刷新控件时将任何处理程序与元素一起克隆。
这很简单lol(适用于所有浏览器[除了opera]):
$('input[type=file]').each(function(){
$(this).after($(this).clone(true)).remove();
});
JS Fiddle: http://jsfiddle.net/cw84x/1/