我正在用VS2012和Javascript开发一个地铁应用程序
我想重置我的文件输入的内容:
<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />
我该怎么做呢?
我正在用VS2012和Javascript开发一个地铁应用程序
我想重置我的文件输入的内容:
<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />
我该怎么做呢?
当前回答
这是最好的解决方案:
input.value = ''
if(!/safari/i.test(navigator.userAgent)){
input.type = ''
input.type = 'file'
}
在所有的答案中这是最快的解。没有输入克隆,没有窗体重置!
我在所有浏览器中都检查了它(它甚至支持IE8)。
其他回答
我在这里错过了另一个解决方案(2021年): 我使用FileList与文件输入交互。
因为没有办法创建FileList对象,所以我使用DataTransfer,它带来了干净的FilleList。
我用:
file_input.files=new DataTransfer().files
在我的例子中,这非常适合,因为我只通过FileList与封装的文件输入元素进行交互。
特别是对于Angular来说
document.getElementById('uploadFile').value = "";
会工作,但是如果你使用Angular呢 它会说“属性‘value’在类型‘HTMLElement’.any上不存在”
document.getElementById()返回不包含value属性的HTMLElement类型。因此,将它转换为HTMLInputElement
(<HTMLInputElement>document.getElementById('uploadFile')).value = "";
额外的:-
然而,我们不应该在angular中使用DOM操作(document.xyz())。
为此,angular提供了@ViewChild、@ViewChildren等,分别是document.querySelector()、document.queryselectorAll()。
连我都没读过。最好关注专家的博客
通过这个link1和link2
使用angular,你可以创建一个模板变量,并将其值设置为null
<input type="file" #fileUploader />
<button (click)="fileUploader.value = null">Reset from UI</button>
或者你可以像这样创建一个方法来重置
component.ts
@ViewChild('fileUploader') fileUploader:ElementRef;
resetFileUploader() {
this.fileUploader.nativeElement.value = null;
}
模板
<input type="file"/>
<button (click)="resetFileUploader()">Reset from Component</button>
stackblitz试样
解决方案
下面的代码是用jQuery编写的。它适用于所有浏览器,并允许保存事件和自定义属性。
var $el = $('#uploadCaptureInputFile');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();
DEMO
有关代码和演示,请参阅jsFiddle。
链接
有关更多信息,请参见如何使用JavaScript重置文件输入。
var fileInput = $('#uploadCaptureInputFile');
fileInput.replaceWith(fileInput.val('').clone(true));