是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:
$('#control').attr({ value: '' });
但这并不奏效。
是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:
$('#control').attr({ value: '' });
但这并不奏效。
当前回答
你可以像这样用它的克隆来替换它
var clone = $('#control').clone();
$('#control').replacewith(clone);
但这个克隆与它的价值太,所以你最好喜欢这样
var emtyValue = $('#control').val('');
var clone = emptyValue.clone();
$('#control').replacewith(clone);
其他回答
简单回答:换掉它。
在下面的代码中,我使用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);
这可以防止在刷新控件时将任何处理程序与元素一起克隆。
function clear() {
var input = document.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('value', '');
input.setAttribute('id', 'email_attach');
$('#email_attach').replaceWith( input.cloneNode() );
}
我一直在寻找简单而干净的方法来清除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>
这很简单lol(适用于所有浏览器[除了opera]):
$('input[type=file]').each(function(){
$(this).after($(this).clone(true)).remove();
});
JS Fiddle: http://jsfiddle.net/cw84x/1/
出于明显的安全原因,您不能设置文件输入的值,甚至是空字符串。
你所要做的就是重置字段所在的表单,或者如果你只想重置包含其他字段的表单的文件输入,使用这个:
function reset_field (e) {
e.wrap('<form>').parent('form').trigger('reset');
e.unwrap();
}
这里有一个例子:http://jsfiddle.net/v2SZJ/1/