javascript 使用Jquery点击隐藏文件上传按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23612483/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:13:32  来源:igfitidea点击:

Use Jquery to click a hidden file upload button?

javascriptjquerybuttonfile-uploadclick

提问by Pomster

I have a hidden file upload as it looks really bad, I have displayed a nicer looking button and would like it to click the hidden file upload when its clicked.

我有一个隐藏文件上传,因为它看起来很糟糕,我已经显示了一个更好看的按钮,并希望它在点击时点击隐藏文件上传。

function ClickUpload() {
    $("#FileUpload").trigger('click');
}

<div id="MyUpload">
    <span id="FileName">Choose File</span>
    <input id="uploadButton" type="button" value="Upload" onclick="ClickUpload()"> 
</div>
<div id="hideUglyUpload">
    <input type="file" name="FileUpload" id="FileUpload"/>
</div>

So far i can move into the function ClickUpload() but it just passes through the click without the file selection window popup.

到目前为止,我可以进入函数 ClickUpload() 但它只是通过单击而没有弹出文件选择窗口。

采纳答案by nicael

Strange that it doesn't work. Try

奇怪的是它不起作用。尝试

<input id="uploadButton" type="button" value="Upload" onclick='$("#FileUpload").click()'> 

回答by silverfighter

I prefer not to have inline JS function calls in markup ... so a little change...

我不喜欢在标记中使用内联 JS 函数调用......所以有点改变......

   $(document).ready(function() {
      $('#uploadButton').on('click',function(evt){
         evt.preventDefault();
         $('#FileUpload').trigger('click');
     });
  });

<div id="MyUpload">
    <span id="FileName">Choose File</span>
    <input id="uploadButton" type="button" value="Upload"> 
</div>
<div id="hideUglyUpload">
    <input type="file" name="FileUpload" id="FileUpload"/>
</div>