文件输入标签点击的解决方法(Firefox)

Mår*_*röm 10 html firefox label file-upload

<label for="input">Label</label><input type="file" id="input"/>
Run Code Online (Sandbox Code Playgroud)

在Firefox 7中,无法通过单击标签来触发打开的文件对话框.

这个问题非常相似,但是用绿色检查它是FF中的一个错误.我正在寻找一种解决方法.

有任何想法吗?

Cor*_*nis 23

谢谢你这个q&a ...帮我解决了.

我的变种@ marten-wikstrom的解决方案:

if($.browser.mozilla) {
  $(document).on('click', 'label', function(e) {
    if(e.currentTarget === this && e.target.nodeName !== 'INPUT') {
      $(this.control).click();
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

笔记

  • $(function() {...});在任一解决方案中都不需要使用document.ready(). jQuery.fn.live在@ marten-wikstrom案件中处理这件事; document在我的例子中明确绑定到了.
  • 使用jQuery.fn.on...当前推荐的绑定技术.
  • 添加了!== 'INPUT'检查以确保执行不会在循环中被捕获:

    <label>
      <input type="file">
    </label>
    
    Run Code Online (Sandbox Code Playgroud)

    (因为文件字段点击会冒泡回到标签)

  • 更改event.target检查event.currentTarget,允许初始点击<em>in:

    <label for="field">click <em>here</em></label>
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用label元素的control属性来实现更清晰,更简单,基于规范的表单字段关联.

  • 请注意,此问题已在FF 22中修复,因此脚本双打开文件对话框.我建议以下脚本更新,但奇怪的是它被评论者拒绝,仍然建议的脚本正常工作.http://stackoverflow.com/review/suggested-edits/2481980 (3认同)