如何跟踪是否使用 javascript 选择了文件?

发布于 2024-10-08 12:10:36 字数 188 浏览 0 评论 0原文

因此,如果我有一个输入字段:

<input type="file" name="file" id="file" />

我单击它并选择一个文件,当我按 Open 时,我想提交表单并上传文件,而无需单击 添加的按钮;

So If I have an input field:

<input type="file" name="file" id="file" />

I click it and select a file and when I press Open I would like to submit the form and upload the file without clicking the button added by <input>.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吻泪 2024-10-15 12:10:36

正如 goreSplatter 下面指出的那样,请注意,就用户体验而言,这种行为并不令人意外。例如,使用像 GMail 这样将文件附加到电子邮件的东西来做到这一点可能是完全有效的;但除非用户有机会取消这些附件等,否则在事情最终确定之前,您可能会陷入用户体验的困境。但我希望您可能已经解决了用户体验方面的问题,并且没有做一些愚蠢的事情。 :-)

回答问题:您可以使用 change 事件处理程序来完成此操作,例如 onchange= 或通过 addEventListener 的 DOM2 等效项(或 IE 上的 attachEvent)。

示例(Live Copy):

hookEvent(document.getElementById('fileInput'),
          'change',
          inputChanged);

function inputChanged() {
  display("The input's value changed");
}

...其中 hookEvent 是用于连接的实用函数一个事件处理程序(请参阅下面的链接了解一个示例,但它尚未优化;如果您使用像 jQuery 这样的库,原型YUI、关闭其他任何一个,它们将包含一种跨浏览器挂钩事件的方法)。

上面链接的示例适用于 Linux 上的 Chrome、Firefox 和 Opera,Windows 上的 IE6 和 IE7,因此总体上很可能得到良好的支持。

As goreSplatter points out below, be careful that this behavior isn't a surprise in terms of the user experience. For instance, it may be perfectly valid to do this with something that attaches files to an email like GMail does; but unless the user has an opportunity to cancel those attachments, etc., before things are finalized, you might be falling down a UX pothole. But I expect you've probably already worked out the UX aspect and are not doing something silly. :-)

Answering the question: You can do this by using a change event handler, e.g., onchange= or the DOM2 equivalent via addEventListener (or attachEvent on IE).

Example (live copy):

hookEvent(document.getElementById('fileInput'),
          'change',
          inputChanged);

function inputChanged() {
  display("The input's value changed");
}

...where hookEvent is your utility function for hooking up an event handler (see the link below for one example, but it's not optimized; if you use a library like jQuery, Prototype, YUI, Closure, or any of several others, they'll include a means of hooking events cross-browser).

The example linked above works on Chrome, Firefox, and Opera for Linux, IE6 and IE7 on Windows, and so is fairly likely to be well-supported overall.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文