问题描述
是否有机会检测用户为 file
元素类型的 HTML input
所做的每个文件选择?
Is there any chance to detect every file selection the user made for an HTML input
of type file
element?
这之前被问过很多次,但如果用户再次选择相同的文件,通常建议的 onchange
事件不会触发.
This was asked many times before, but the usually proposed onchange
event doesn't fire if the user select the same file again.
推荐答案
在每个 onclick
事件上将 input
的值设置为 null
.即使选择了相同的路径,这也会重置 input
的值并触发 onchange
事件.
Set the value of the input
to null
on each onclick
event. This will reset the input
's value and trigger the onchange
event even if the same path is selected.
var input = document.getElementsByTagName('input')[0];
input.onclick = function () {
this.value = null;
};
input.onchange = function () {
console.log(this.value);
};
<input type="file" value="C:fakepath">
注意:如果您的文件以C:fakepath"为前缀是正常的.这是一项安全功能,可防止 JavaScript 知道文件的绝对路径.浏览器内部仍然知道它.
Note: It's normal if your file is prefixed with 'C:fakepath'. That's a security feature preventing JavaScript from knowing the file's absolute path. The browser still knows it internally.
这篇关于HTML 输入文件选择事件在选择同一文件时不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!