繁体   English   中英

<input type="“file”">导航回页面时再次触发更改事件

[英]<input type=“file”> change event firing again when navigating back to the page

我有一个非常基本的文件上传器。 我上传了一个文件,它触发了更改事件(console.log)。 我导航到另一个页面,然后按返回按钮。 更改事件再次触发(事件再次记录到控制台)。

我正在使用 Chrome。 文本输入不会发生这种情况; 只有文件。 有谁知道为什么?

<input type="file" />

<script>
    const input = document.querySelector("input[type=file]");
    input.addEventListener("change", console.log, { once: true });
</script>

使用 Chromium (Brave) 文件似乎被缓存了。 所以,当你 go 回来时,文件被加载回输入,触发了change事件。

一种解决方法是在页面加载时将输入值设置为空字符串:

<input type="file" />

<script>
    const input = document.querySelector('input[type=file]');

    window.addEventListener('load', () => (input.value = ''));
    input.addEventListener('change', console.log);
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM