我正在尝试模拟 input[type=file]
通过正常<button>
,在大多数情况下它运行良好,但有时 change
事件不会被触发。
var count = 0;
button.addEventListener('click', function (e) {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.onchange = function (e) {
const file = e.target.files && e.target.files[0];
if (file) {
$('span').text(`file size: ${file.size}, action count: ${++ count}`);
}
};
document.body.appendChild(input);
input.click();
document.body.removeChild(input);
}, false)
以下是重现问题的步骤:
- 单击按钮,然后选择一个文件。
- 查看操作计数是否增加。
- 重复上述步骤
通常情况下,每次选择文件后,操作计数都会增加 1,即使是与之前相同的文件(因此这不是值未更改的问题)。
但是,有时选择文件后,什么也没有发生。事实上,这种情况经常发生,但不规律。例如,我只是重复上述步骤 7 次,结果发生了事件丢失。有时要重复几十遍才输。对于经常选择文件的用户来说,这成为一个明显的问题。
这似乎只发生在 Chrome 上,在 Chrome 48-51 上重现,我想知道是否有人碰巧遇到同样的问题并找到解决方案?谢谢。
最佳答案
重用输入元素有助于:
const input = document.createElement('input');
input.type = 'file';
button.addEventListener('click', function() {
input.onchange = function() {
// deal with input.files here
};
input.value = '';
input.click();
}, false);
在您的情况下,甚至不需要每次都替换 input.onchange
,因为它不依赖于按钮的 onClick
处理程序的关闭(因此您只需重置值并触发点击事件),但我决定以这种方式编写它,以防有人确实需要关闭(就像我一样)。
将 input.click()
放入 setTimeout
中似乎也有帮助,但随后它在较重的页面上崩溃了。
至于为什么会发生这种情况 - 我不知道。已经挖掘和调试了几个小时,什么也没有。有一个very similar question在你的一个月后发布,仍然没有回复。
关于javascript - input[type=file] 更改事件在 Chrome 上偶尔会丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38845015/