简体   繁体   English

触发单击非隐藏输入字段

[英]Trigger click on non-hidden input field

So I am trying to do the standard "have a button trigger a file input field" thing. 因此,我正在尝试执行标准的“具有按钮触发文件输入字段”操作。 However, I haven't even gotten to hiding the input field yet - right now it is visible on the page along with the button that should trigger the click. 但是,我什至还没有隐藏输入字段-现在,它与应该触发单击的按钮一起在页面上可见。 However, it is not working. 但是,它不起作用。

<body>
    <button id="uploadDocument" type="button" class="btn btn-primary btn-lg">
        <span>Check In</span>
    </button>
    <input id="fileupload" type="file" name="files[]" />
</body>
<script type="text/javascript">
    $(document).ready(function() {
        $("#uploadDocument").on("click", function() {
            $("#fileupload").trigger("click");
       });
    });
</script>

For whatever reason, this doesn't work. 无论出于什么原因,这都不起作用。 Like I said, and as you can see, the input field is not hidden - it's right there on the page. 就像我说的那样,正如您所看到的,输入字段并未隐藏-它就在页面上。 Nothing happens at all. 什么都没发生。 If you debug it and put breakpoints in the code, it never gets hit. 如果您调试它并在代码中放置断点,它将永远不会被击中。 I figure it's gotta be something obvious, but I've racked my brain and I can't figure it out. 我认为这肯定是显而易见的,但是我已经绞尽脑汁,无法弄清楚。

https://github.com/blueimp/jQuery-File-Upload/wiki/Style-Guide https://github.com/blueimp/jQuery-File-Upload/wiki/Style-Guide

Why isn't it possible to programmatically trigger the file input selection? 为什么无法以编程方式触发文件输入选择?

Most browsers prevent submitting files when the input field didn't receive a direct click (or keyboard) event as a security precaution. 为了安全起见,当输入字段未收到直接单击(或键盘)事件时,大多数浏览器都会阻止提交文件。 Some browsers (eg Google Chrome) simply prevent the click event, while eg Internet Explorer doesn't submit any files that have been selected by a programmatically triggered file input field. 某些浏览器(例如Google Chrome)仅阻止单击事件,而Internet Explorer则不提交通过程序触发的文件输入字段选择的任何文件。 Firefox 4 (and later) is so far the only browser with full support for invoking "click"-Events on a completely hidden (display: none) file input field. 到目前为止,Firefox 4(及更高版本)是唯一完全支持调用“ click”-完全隐藏(显示:无)文件输入字段中的事件的浏览器。

you should trigger onchange not click 你应该触发onchange而不是点击

<script type="text/javascript">
$(document).ready(function() {
    $("#uploadDocument").on("click", function() {
        $("#fileupload").trigger("change");
   });
});

check here jsfiddle 在这里检查jsfiddle

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

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