jQuery jquery触发器:单击文本链接时如何触发输入中的浏览文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7132553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery trigger: how can I trigger the browse file in the input when I click on a text link?
提问by laukok
Following up on this post, I have another issuer - how can I trigger the browse file in the input when I click on a text link?
跟进这篇文章,我有另一个发行者 - 当我点击文本链接时,如何触发输入中的浏览文件?
Basically I want to hide the form but it will be triggered when you click on the upload text link.
基本上我想隐藏表单,但当你点击上传文本链接时它会被触发。
<a href="#" class="upload">upload</a>
<form action="upload.php" method="post" enctype="multipart/form-data" id="myForm" style="display:none;">
<input type="file" multiple="multiple" name="file[]" />
<input type="submit" name="upload" value="Submit"/>
</form>
<div id="output"></div>
This is my working Javascript code:
这是我的工作 Javascript 代码:
$(document).ready(function(){
$('.upload').click(function(){
$(this).trigger($('input[type=file]'));
return false;
});
$('input[type=file]').change(function() {
$('#myForm').ajaxSubmit({
target: '#output'
});
});
});
回答by Joe
You can't use style="display:none;"
use style="visibility:hidden;"
你不能使用style="display:none;"
使用style="visibility:hidden;"
and I changed trigger to click:
我将触发器更改为单击:
$('.upload').click(function(){
$('input[type=file]').click();
return false;
});
Reasoning推理:
The input fields will not be sent to the server with display:none
, but will be with visibility:hidden
.
输入字段不会用 发送到服务器display:none
,但会用visibility:hidden
。
回答by link0047
why don't you use a label instead? then you could use the for attribute.
你为什么不使用标签呢?那么你可以使用 for 属性。
<style type="text/css">
#file_upload {
visibility: hidden;
}
</style>
<a href="#" class="upload">
<label for="file_upload">upload</label
</a>
<form action="upload.php" method="post" enctype="multipart/form-data" id="myForm">
<input id="file_upload" type="file" multiple="multiple" name="file[]" />
<input type="submit" name="upload" value="Submit"/>
</form>
<div id="output"></div>
回答by Neal
Joe's method is correct. However, this solution will only work in some browsers. It works on Chrome and Firefox but not on Opera, Safari, or the Android Galaxy S built-in browser (tested on current versions as of June 23, 2012). Those browsers likely disable triggering the upload button via JS for security reasons.
乔的方法是正确的。但是,此解决方案仅适用于某些浏览器。它适用于 Chrome 和 Firefox,但不适用于 Opera、Safari 或 Android Galaxy S 内置浏览器(在截至 2012 年 6 月 23 日的当前版本上测试)。出于安全原因,这些浏览器可能会禁用通过 JS 触发上传按钮。
I will update this post if I find a solution that works in all modern browsers
如果我找到适用于所有现代浏览器的解决方案,我会更新这篇文章
回答by Omkar Frozen
<button>
<label>
select file
<input type="file" style="visibility: hidden" file-handler>
</label>
</button>
This should help you
这应该可以帮助你