【问题标题】:hidden Input type='file' is not triggering when its parent div has been clicked单击其父 div 时隐藏的 Input type='file' 未触发
【发布时间】:2013-12-13 03:32:19
【问题描述】:

抱歉,如果您发现此问题重复,但我环顾四周,尝试过,失败了,所以需要您的帮助。

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>

one.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 超出最大调用堆栈大小

我不知道发生了什么,如果是 jquery 版本的问题? 你能帮我么?一个工作代码示例或者一个 jsfiddle? 提前谢谢你:)

【问题讨论】:

  • 你试过$('#myfile').click();$('#myfile').focus();吗?
  • 都试过了。不工作!

标签: javascript css jquery jquery-click-event


【解决方案1】:

您需要在 dom 就绪处理程序中添加点击处理程序,因为在执行 one.js 时,dom 结构中不存在 add-image 元素

jQuery(function ($) {
    $("#add-image").click(function () {
        $("#myfile").click();
    });
})

Dom Ready

由于文件输入元素在myfile元素内,触发文件元素上的点击元素将导致递归错误提示callstack exceeded

解决方法是将文件元素移出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

【讨论】:

  • 不工作阿伦。抛出这样的错误: event.returnValue 已弃用。请改用标准 event.preventDefault()。未捕获的 RangeError:超出最大调用堆栈大小
  • event.returnValue is deprecated 是新版本浏览器中的警告...希望 jQuery 将在新版本中处理它
  • 您能否提供更多有关调用堆栈问题的信息
  • 是什么意思?我只是从控制台发出错误警告。没有别的了。
  • 我知道。但是文件上传对话没有打开。
【解决方案2】:

将您的 html 更改为

     <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>
    <input type="file" id="myfile" style="display:none" />

【讨论】:

    【解决方案3】:

    我认为 kyou 错过了 dom 就绪处理程序。
    试试这个:

    $(document).ready(function(){
      $("#add-image").click(function(){
         $("#myfile").trigger('click');
      });
    });
    

    【讨论】:

    • event.returnValue 已弃用。请改用标准 event.preventDefault()。未捕获的 RangeError:超出最大调用堆栈大小
    猜你喜欢
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    相关资源
    最近更新 更多