文件输入更改事件仅触发一次 [英] Files input change event fires only once

查看:122
本文介绍了文件输入更改事件仅触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了一些HTML5文件功能制作了一个小脚本,它允许您选择一个或多个文件,并且每次都会写入文件的名称。一切都按原样运行,只有检测文件输入的值变化的事件只触发一次,那么如何才能使每次更改都触发,而不仅仅是第一次更改?

I've made a small script using some of the HTML5 files features, which allows you to select one or more files, and each time it will write the name of the file(s). Everything works as it should, only the event to detect the value change of the files input fire only once, so how can I make it fire every change and not only on the first change?

顺便说一句,这就是我所做的:
http://tamir.netspot.co .il / html5 / files /

By the way, here is what I made: http://tamir.netspot.co.il/html5/files/

推荐答案

似乎更改正在删除事件侦听器,因为您正在使用 innerHTML 来更新相同的元素( wrapper )输入本身就在里面。所以包装器元素的内容 - 包括文件输入 - 正在重新呈现,并且一路上,事件监听器被删除(或者,它被连接到一个不再存在的元素。

It appears that the change event listener is being removed because you're using innerHTML to update the same element (wrapper) that the input itself is inside. So the contents of the wrapper element – including the file input – is being re-rendered, and along the way, the event listener is removed (or, rather, it's connected to an element that's no longer there).

这是一个简单的jsfiddle 与您的代码完全相同,只是它将选定的文件名打印在与输入所在元素不同的元素中。它可以工作(无论如何都在WebKit中)

Here's a simple jsfiddle that does exactly the same as your code, except that it prints the selected file names in a different element than the element the input is in. And it works (in WebKit, anyway)

这是进一步的证明(我基本上复制了你的代码,只添加了一行代码修改 wrapper.innerHTML 后注册事件监听器

Here's further proof (I basically copied your code, and only added a line to re-register the event listener after the modification of wrapper.innerHTML)

所以,更改事件 会针对每次更改触发,但是通过在输入上使用 innerHTML 来删除正在观察的输入父元素。

So, the change event does fire for each change, but the input that's being observed is removed by the use of innerHTML on the input's parent element.

我诚实我不知道这是否是合法的浏览器错误。对于 innerHTML 而言,覆盖现有的输入元素是有道理的,但浏览器足够聪明,不会重置输入的值,所以你认为听众会留下来太......所以......好吧,这让人很困惑

I honestly don't know whether this is a legitimate browser bug or not. It makes sense for innerHTML to "overwrite" the existing input element, yet the browser is smart enough to not not reset the input's value, so you'd think listeners would stick around too… so… well, it's confusing

这篇关于文件输入更改事件仅触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆