简体   繁体   English

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

[英]<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.

相关问题 JS-输入类型文件触发更改时没有更改 - JS- Input type file firing change evt when there is no change 当输入的值为空格时,输入类型 = 电子邮件的更改事件不会触发 - Input type=email's change event is not firing when the value entered is whitespace Firefox在input.attr(“ type”,“ number”)上触发更改事件 - Firefox firing change event on input.attr(“type”, “number”) 输入类型=文件onchange事件未在google chrome / firefox中触发 - input type=file onchange event is not firing in google chrome/firefox 通过代码操纵输入时,不会触发主干视图更改事件 - Backbone view change event not firing when input manipulated by code 当输入值从 VueJS 更改时,JQuery 更改事件未触发 - JQuery change event not firing when input value changed from VueJS 导航后退/卸载事件未触发时,iOS 5 Safari中的页面缓存问题 - Problems with Page Cache in iOS 5 Safari when navigating back / unload event not fired 输入[类型=“文件”]上的JavaScript更改事件 - JavaScript change event on input[type=“file”] 输入类型为隐藏时,更改事件不起作用 - on change event not working when input type is hidden 导航到页面时触发“后退按钮”事件 - 'backbutton' event fired when navigating to a page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM