【问题标题】:How to trigger click on input file element by clicking on another element如何通过单击另一个元素触发单击输入文件元素
【发布时间】:2017-11-21 19:10:10
【问题描述】:

我在按钮上使用 jQuery 和 Ajax,更新输入文件上传元素上的属性“accept”的值,然后触发点击它。但我只能在 Firefox 上做到这一点。在 Chrome 上,触发点击事件不起作用,在 IE8 上,它起作用但无法上传所选文件。我应该怎么办? 这是我在 handleAjaxResponseSuccess 函数中的代码:

$('#inputFile').attr('accept', '.jpg, .png');
$('#inputFile').click();
//in Firefox and IE8, it shows a file dialog that allows choosing file to upload. But in Chrome, the file dialog does not appear, and in IE8, the selected file cannot be uploaded

我的 HTML 代码

<button type="button" id="uploadBtn" onclick="getAcceptedExtension()"title="Upload" class=""></button>
<input type="file" name="" id="inputFile" multiple="multiple"style="display: none;" >

【问题讨论】:

  • On Chrome, the trigger click event doesn't work 这是设计使然。在某些浏览器中,出于安全原因,您不能在文件输入上伪造事件。 accept 仅适用于 IE10 及更高版本,根本不适用于 Edge。查看 MDN 兼容性表:developer.mozilla.org/en-US/docs/Web/HTML/Element/…
  • 我可以看到这个。这种情况有解决办法吗?
  • 不可靠,不。即使有,它也可能会被未来的浏览器更新破坏。您需要创建 UI,以便用户必须启动 fie 打开对话框
  • 所以你的意思是用户必须直接点击输入文件,对吧?
  • 是的,没错

标签: javascript jquery html file-upload


【解决方案1】:

一种基本且简单的方法是:

$('#b1').on('click',function(){
    alert("button #1 is clicked");
    $('#b2').click();
});
$('#b2').on('click',function(){
    alert("button #2 is clicked");
});

Jsfiddle:https://jsfiddle.net/vf65pzhj/1/

【讨论】:

    【解决方案2】:

    出于安全原因,某些浏览器不允许直接触发文件输入。 打开对话框的操作必须由用户交互调用(例如单击),并且输入文件必须可见(显示!= none)并具有焦点。

    您可以显示打开对话框并隐藏后像这样:

    getAcceptedExtension = function() {
      $('#inputFile').attr('accept', '.jpg, .png');
      $('#inputFile').show();
      $('#inputFile').focus();
      $('#inputFile').click();
      $('#inputFile').hide();
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button type="button" id="uploadBtn" onclick="getAcceptedExtension()"title="Upload" class="">CLICK ME</button>
    <input type="file" name="" id="inputFile" multiple="multiple"style="display: none;" >

    【讨论】:

    • 我试图将它应用到我的代码中,但它仍然不起作用。顺便说一句,谢谢。
    猜你喜欢
    • 2012-05-08
    • 2016-04-06
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多