很抱歉,如果您发现这个问题重复,但我环顾四周,尝试过,失败了,所以需要您的帮助。
one.html
<html>
<head>
<link rel="stylesheet" href="one.css" >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="one.js"></script>
</head>
<body>
<div class='some-class' id="add-image">
<input type="file" id="myfile" style="display:none" />
<h4> I want to open the file upload dilogue when anywhere of this div has been clicked</h4>
</div>
</body>
</html>
一个.css
.some-class{
border: 1px solid grey;
}
h4{
text-align:center;
}
one.js
$("#add-image").click(function(){
$("input[id='myfile']").click();
});
有时显示
event.returnValue 已弃用。请改用标准的 event.preventDefault()。
有时
uncaught rangeerror maximum call stack size exceeded
我不知道发生了什么,如果是 jquery 版本的问题? 你能帮我么?一个工作代码示例或者一个 jsfiddle? 提前谢谢你:)
最佳答案
您需要在 dom 就绪处理程序中添加点击处理程序,因为当执行 one.js
时,dom 结构中不存在 add-image
元素
jQuery(function ($) {
$("#add-image").click(function () {
$("#myfile").click();
});
})
由于文件输入元素在 myfile
元素中触发文件元素上的点击元素将导致递归错误,显示 callstack exceeded
解决办法是将file元素移出myfile
元素
<input type="file" id="myfile" style="display:none" />
<div class='some-class' id="add-image">
<h4> I want to open the file upload dilogue when anywhere of this div has been clicked</h4>
</div>
演示:Fiddle
关于javascript - 单击其父 div 时,隐藏的输入类型 ='file' 不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20243359/