如何在文件选择上触发事件

pta*_*mzz 82 javascript jquery

我有一张表格

<form  onSubmit="return disableForm(this);" action="upload.php" method="post" name="f" id="wizecho" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button onClick="return disableForm(this),ajaxUpload(this.form,'wizecho_upload.php', '&lt;br&gt;Uploading image please wait.....&lt;br&gt;'); return false;">
        Upload Image
    </button>
</form>
Run Code Online (Sandbox Code Playgroud)

它是上传图像.

在这里,我需要单击按钮上传图像,我将使用onClick事件.我想删除上传按钮,一旦在输入中选择了文件,我就想触发该事件.我怎么做??

Vin*_*nie 116

在文件输入上使用change事件.

$("#file").change(function(){
         //submit the form here
 });
Run Code Online (Sandbox Code Playgroud)

  • 当你异步提交表单时会发生什么,不要离开页面,然后尝试再次上传同一个文件?此代码仅执行一次,第二次,选择同一文件将不执行更改事件 (29认同)
  • @ChristopherThomas的反对意见正是我在这里的原因,幸运的是,下面有一个很好的回应解决了它,多年后:http://stackoverflow.com/a/40581284/4526479 (4认同)
  • 答案不使用纯JavaScript的事实是错误的 (3认同)
  • 当我再次选择同一个文件时,不会触发更改事件。有什么其他方法可以每次都有效吗? (2认同)

Dar*_*rov 64

您可以在输入字段上订阅onchange事件:

<input type="file" id="file" name="file" />
Run Code Online (Sandbox Code Playgroud)

然后:

document.getElementById('file').onchange = function() {
    // fire the upload here
};
Run Code Online (Sandbox Code Playgroud)


app*_*her 44

这是一个较老的问题,需要一个更新的答案,以解决@Christopher Thomas在接受答案的评论中所关注的问题.如果您不离开页面然后再次选择文件,则需要在单击或执行touchstart(移动设备)时清除该值.即使您离开页面并使用jquery,下面的内容也会起作用:

//the HTML
<input type="file" id="file" name="file" />



//the JavaScript

/*resets the value to address navigating away from the page 
and choosing to upload the same file */ 

$('#file').on('click touchstart' , function(){
    $(this).val('');
});


//Trigger now when you have selected any file 
$("#file").change(function(e) {
    //do whatever you want here
});
Run Code Online (Sandbox Code Playgroud)

  • 我的问题是使用`element.setAttribute(“ value”,“”)`如果您不使用jQuery,则需要使用`element.value =“”`来使文件元素真正正确清除。 (2认同)

小智 5

使用 es6 的普通 js

document.querySelector('input[name="file"]').addEventListener('change', (e) => {
 const file = e.target.files[0];
  // todo: use file pointer
});
Run Code Online (Sandbox Code Playgroud)