简体   繁体   English

通过javascript触发输入[type = file]

[英]Trigger input[type=file] via javascript

I'm trying to trigger the click event of an <input type="file" /> via javascript (onclick the file selection dialogue should open). 我试图通过javascript触发<input type="file" />的click事件(onclick文件选择对话框应打开)。 So far I've tried: 到目前为止,我已经尝试过:

$('#uploadFile').trigger('click')
.trigger('submit')
.submit()
.post(); // Stacked for brevity

No dice. 没有骰子。

Is there something special about this input that prevents these approaches from working? 此输入是否有某些特殊之处阻止这些方法起作用?

Here's a Fiddle . 这是小提琴

some of the default actions of events are prevented by the browser if the event is triggered by a script and is not done in a user initialized thread for security reasons. 如果事件是由脚本触发的,并且出于安全原因未在用户初始化的线程中完成,则浏览器会阻止事件的某些默认操作。

See it working if it is triggered from a another click handler(User has to click the button) 如果它是由另一个单击处理程序触发的,则它可以正常工作(用户必须单击按钮)

$('button').click(function(){
    $('#uploadFile').trigger('click')
})

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM