解决用input选择文件不能选择同一个文件
在 JavaScript 中,默认情况下,使用 <input type="file">
选择文件时,如果连续两次选择同一个文件,第二次选择不会触发 change
事件(因为文件路径未改变)。若需要允许重复选择同一个文件并触发操作,可以通过手动重置input.value
来解决
<input type="file" id="fileInput"><script>const fileInput = document.getElementById('fileInput');fileInput.addEventListener('change', function(e) {// 1. 获取选中的文件const file = e.target.files[0];if (!file) return;// 2. 执行你的操作(如读取文件、上传等)console.log('已选择文件:', file.name);// 3. 重置 input.value,允许下次选择同一文件e.target.value = ''; });
</script>