javascript 无法清除javascript jquery中的输入类型=文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11866757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't clear input type=file in javascript jquery
提问by anmarti
Possible Duplicate:
Clearing <input type='file' /> using jQuery
This is my code:
这是我的代码:
<input ID="fileUpload1" runat="server" type="file" style="width:275px; position:absolute; left:1px"/>
I've try some solutions:
我尝试了一些解决方案:
$("input[type='file']").val('');
$('#DivfileUpload').replaceWith("<input class=VWButton ID=fileUpload1 runat=server type=file style=width:275px; position:absolute; left:1px/>");
and many others from the web but no succeed.
以及来自网络的许多其他人,但没有成功。
回答by Quentin
You cannot set the value of a file input for (obvious) security reasons.
出于(明显的)安全原因,您不能设置文件输入的值。
If you want to clear it, you need to reset the form it is in.
如果要清除它,则需要重置它所在的表单。
Replacing it with a new one should also work, but do it with valid code. (which means don't try to include server side code such the ASP runat=server
attribute/value and do quote attribute values that aren't plain words (e.g. your style attribute)).
用新的替换它也应该可行,但要使用有效的代码。(这意味着不要尝试包含服务器端代码,例如 ASPrunat=server
属性/值,并引用不是简单词的属性值(例如您的样式属性))。
回答by Doug Sheffer
Attempting to set the value with .val('') will fail in some browsers (like IE) for security reasons.
出于安全原因,尝试使用 .val('') 设置值将在某些浏览器(如 IE)中失败。
Your best options is to reset the form:
您最好的选择是重置表单:
$('form').trigger('reset');
Or to use your replacement code, with slight modification (making sure the HTML valid):
或者使用您的替换代码,稍作修改(确保 HTML 有效):
$('#fileUpload1').replaceWith('<input id="fileUpload1" type="file" style="width:275px; position:absolute; left:1px"/>');
If you style the box with CSS, your code becomes even simpler.
如果您使用 CSS 设置框的样式,您的代码会变得更加简单。
The CSS:
CSS:
#fileUpload1 {
width: 275px;
position: absolute;
left: 1px;
}
The JavaScript:
JavaScript:
$('#fileUpload1').replaceWith('<input id="fileUpload1" type="file"/>');
A more advanced option is to hide the file upload box when the page is loaded, then create a clone of it that gets shown to the user. When you need to clear it, you delete the clone, then re-clone the original hidden one. This method also allows you to make multiple copies of the input box if you want to allow the user to upload more than one file. I will leave the implementation details up to you. ;)
一个更高级的选项是在加载页面时隐藏文件上传框,然后创建它的克隆以显示给用户。当你需要清除它时,你删除克隆,然后重新克隆原来隐藏的。如果您希望允许用户上传多个文件,此方法还允许您制作输入框的多个副本。我将把实现细节留给你。;)
回答by hawx
$(function() {
$('#fileUpload1').val('');
});