是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:
$('#control').attr({ value: '' });
但这并不奏效。
是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:
$('#control').attr({ value: '' });
但这并不奏效。
当前回答
文件输入的值是只读的(出于安全原因)。不能通过编程方式使其变为空白(除非调用表单的reset()方法,该方法的范围比该字段更广)。
其他回答
简单回答:换掉它。
在下面的代码中,我使用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);
这可以防止在刷新控件时将任何处理程序与元素一起克隆。
.clone()东西在Opera(可能还有其他)中不起作用。它保存内容。
对我来说,这里最接近的方法是Jonathan之前的方法,但是确保字段保留其名称、类等,在我的例子中导致了混乱的代码。
像这样的东西可能很管用(也要感谢昆汀):
function clearInput($source) {
var $form = $('<form>')
var $targ = $source.clone().appendTo($form)
$form[0].reset()
$source.replaceWith($targ)
}
function clear() {
var input = document.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('value', '');
input.setAttribute('id', 'email_attach');
$('#email_attach').replaceWith( input.cloneNode() );
}
$("#control").val(")就是你所需要的!使用JQuery 1.11在Chrome上测试
其他用户也在Firefox中进行了测试。
它适用于所有浏览器。
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);
}