Javascript:模拟 <input type="file"> 中的点击

src*_*tro 3 javascript

再会,

我试图模拟单击浏览文件元素,但无法使其工作。

我发现了这个: http://www.randomsnippets.com/2008/03/05/simulate-a-button-click-via-javascript/

并尝试过,它适用于“按钮”和“提交”类型:

<input type="checkbox" onClick="document.getElementById('theSubmitButton').click();">Check the box to simulate a button click
<input type="submit" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将其更改为“文件”类型时:

<input type="checkbox" onClick="document.getElementById('theSubmitButton').click();">Check the box to simulate a button click
<input type="file" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">
Run Code Online (Sandbox Code Playgroud)

它在 Firefox 和 IE8 中不起作用。但文件浏览器窗口出现在 Google Chrome 中。

这种做法有问题吗?我怎样才能使它在 FF 和 IE8 中工作?

非常感谢!

the*_*ejh 5

这是一项安全限制,旨在防止恶意 JavaScript 在用户不希望的情况下从用户计算机上传文件,或者通过打开文件选择对话框来欺骗用户这样做。你不能在 javascript 中做到这一点,这不是一个错误,而是一个功能。

  • 只是对此答案的补充:如果您需要随机打开文件对话框 - 您可以使用基于闪存的上传器。 (2认同)