我如何以编程方式使用JavaScript打开文件选取器? [英] How can I programmatically open the file picker with JavaScript?

查看:107
本文介绍了我如何以编程方式使用JavaScript打开文件选取器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

在JavaScript中,我可以创建一个点击事件消息以编程方式为文件输入元素?

我天真地尝试了以下使用JavaScript以编程方式打开文件选取器(请参阅小提琴此处):

I have naively tried the following to open the file picker programmatically with JavaScript (see fiddle here):

<input type='file'>​

<script>
    $(function () {
        $('input').click();
    });
</script>

以上行不通。我怎样才能用JavaScript打开 input type ='file'的文件选择器?

The above doesn't work. How can I open the file picker of a input type='file' with JavaScript?

推荐答案

出于安全原因,您不能触发对话框,除非它是对某些用户触发事件的响应。您可以通过点击其他元素触发对话框:

For security reasons you can't trigger the dialog, unless it is as a response to some user triggered event. You could for instance trigger the dialog through a click on some other element:

$(function () {
    $(".someElement").click(function () {
        $('#f').click();
    });
});

工作示例

这篇关于我如何以编程方式使用JavaScript打开文件选取器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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