[英]<input type=“file”> change event firing again when navigating back to the page
I have a very basic file uploader.我有一个非常基本的文件上传器。 I upload a file, which triggers the change event (console.log).我上传了一个文件,它触发了更改事件(console.log)。 I navigate to a different page, then press the back button.我导航到另一个页面,然后按返回按钮。 The change event triggers again (the event is logged again to the console).更改事件再次触发(事件再次记录到控制台)。
I am using Chrome.我正在使用 Chrome。 It doesn't happen with text inputs;文本输入不会发生这种情况; only file.只有文件。 Anyone know why?有谁知道为什么?
<input type="file" />
<script>
const input = document.querySelector("input[type=file]");
input.addEventListener("change", console.log, { once: true });
</script>
Using Chromium (Brave) the file seems to be cached.使用 Chromium (Brave) 文件似乎被缓存了。 So, when you go back, the file is loaded back into the input, triggering the change
event.所以,当你 go 回来时,文件被加载回输入,触发了change
事件。
One workaround would be to set the inputs value to an empty string on page-load:一种解决方法是在页面加载时将输入值设置为空字符串:
<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.