我正在用VS2012和Javascript开发一个地铁应用程序

我想重置我的文件输入的内容:

<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />

我该怎么做呢?


当前回答

只使用:

$('input[type=file]').val('');

其他回答

另一种解决方案(不选择HTML DOM元素)

如果你在输入中添加了'change'事件监听器,那么在javascript代码中你可以调用(对于某些特定的条件):

event.target.value = '';

例如在HTML中:

<input type="file" onChange="onChangeFunction(event)">

在javascript中:

onChangeFunction(event) {
  let fileList = event.target.files;
  let file = fileList[0];
  let extension = file.name.match(/(?<=\.)\w+$/g)[0].toLowerCase(); // assuming that this file has any extension

  if (extension === 'jpg') {
    alert('Good file extension!');
  }
  else {
    event.target.value = '';
    alert('Wrong file extension! File input is cleared.');
  }

重置输入文件是非常单一的

$('input[type=file]').val(null);

如果你绑定重置文件中更改表单的其他字段,或者用ajax加载表单。

本例适用

选择器,例如$('input[type=text]')或表单的任何元素

事件单击,更改,或任何事件

$('body').delegate('event', 'selector', function(){
     $('input[type=file]').val(null) ;
});

特别是对于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试样

getElementById (uploadCaptureInputFile”)的文件。价值;