如何在非 IE 浏览器中响应输入类型=文件上的单击事件
因此,场景如下 -
与 StackOverflow 上关于如何调用 input[type=file] 元素上的单击事件的 3000 个其他问题不同,我只想对此做出回应。我正在寻找类似的内容:
<input id="theFile" onclick="var that=this;setTimeout(function(){if(that.value){postTheForm();}}),0);" />
我不想在元素上调用 click() ,我只是想知道何时有人选择了文件,以便我们可以提交表单。在 IE 中,它按预期工作,因为文件对话框会休眠 javascript 线程,直到用户单击对话框中的“打开”或“取消”。在 FireFox 中,对话框似乎不会休眠线程,并且匿名函数会立即触发 - 即使对话框仍然处于运行状态。
我在想我可以使用 onchange 事件,或者 FireFox 中的其他东西来模拟 IE 行为,但到目前为止还没有任何运气。关于如何在用户单击对话框中的“打开”或“取消”后执行代码有什么想法吗?
So here's the scenario-
Unlike the 3000 other questions on StackOverflow about how to INVOKE the click event on an input[type=file] element, I just want to respond to it. I'm looking for something like:
<input id="theFile" onclick="var that=this;setTimeout(function(){if(that.value){postTheForm();}}),0);" />
I'm not trying to call click() on the element, I just want to know when someone has selected a file so it we can submit the form. In IE, it works as expected, because the file dialog box sleeps the javascript thread until the user clicks Open or Cancel in the dialog. In FireFox, it seems like the dialog does not sleep the thread, and the anonymous function fires immediately - even while the dialog is still up.
I was thinking may I could use the onchange event, or something else in FireFox to simulate the IE behavior, but haven't had any luck so far. Any ideas as to how I can execute code AFTER the user clicks Open or Cancel in the dialog?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您单击文件上传时,告诉 jQuery 将其聚焦,当您选择一个文件并单击打开/取消时,它将失去焦点,即
模糊
。我在 Chrome 中测试了这个。
When you click the file upload tell jQuery to focus it, when you select a file and click open/cancel it will lose focus aka
blur
.I tested this in chrome.
使用:
onchange="submitForm()"
use:
onchange="submitForm()"
那么您可以启动一个间隔计时器,每隔 100 毫秒左右检查一次。
问题是,这有点脆弱,因为文件输入的“值”不是完整的路径。但是,由于您无论如何都要提交整个表单,因此用户实际上没有机会多次单击文件元素。
编辑 - 这是假设“更改”事件确实不适合您;我目前没有可用的 Firefox 来查看。
Well you could start up an interval timer to just check every 100 milliseconds or so.
Thing is, this is a little fragile because the "value" of a file input is not a complete path. However, since you're submitting the whole form anyway, the user really doesn't have a chance to click on the file element more than once.
edit — this is presuming that the "change" event really isn't working for you; I don't have Firefox available at the moment to see.