如何使用jquery调用文件输入?

Ras*_*ari 2 html javascript jquery input

我想只通过jquery调用文件输入的click事件,但是当我使用下面的代码时,它不起作用:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="js/jquery.js"></script>
    <script>
        $(function () {
            setTimeout(function () {
                $('#file').trigger('click');
            }, 2000);
        });
    </script>
</head>
<body>
    <input id="file" name="file" type="file" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

注意

我想只用jquery或javascript做这个.

Vic*_*tor 5

去做就对了!

使用jQuery:

$('#file').click();
Run Code Online (Sandbox Code Playgroud)

纯javascript:

var fileInput = document.getElementById('file');
if(fileInput) {
     fileInput.click();
}
Run Code Online (Sandbox Code Playgroud)

$(document).ready(function() {
  $('#btn').click(function() {
    // Will Work!!!!
    $('#fileInput').click();
  });
  // Will not Work
  $('#fileInput').click();
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<input type="file" id="fileInput" />
<br/>
<br/>
<button id="btn">Click</button>
Run Code Online (Sandbox Code Playgroud)

您的问题是我需要click event从用户操作中调用.看看这个例子.在click内部被称为ready事件不工作,因为不是用户的事件.但是click工作中的代码相同.