【问题标题】:jQuery - on button click, emulate input[type="file"].change only in parent elementjQuery - 单击按钮时,仅在父元素中模拟 input[type="file"].change
【发布时间】:2012-07-10 05:03:46
【问题描述】:

我不确定标题是否正确地说明了我正在尝试做的事情,但我不知道如何命名该问题。

我正在尝试使用 css 和 jquery 为 input[type="file"] 元素添加一些样式。这是我的代码:

<div class="input-file">
    <input type="file"><label>Select file...</label><button type="button">...</button>
    </div>

INPUT 有 display: none 样式,因此不可见。

Javascript:

$('.input-file > button').live('click',function() {
$('input[type="file"]').click(); });

如果页面上只有 1 个元素,则效果很好,但如果有例如 3 个,则每当我单击按钮 1 时,它将触发函数 3 次。我希望它只响应它的父元素 &lt;div class="input-file"&gt;

我如何使用 .parent 或 .before 或任何可以实现此目的的函数?

编辑:

@Chandu 有一个很好的解决方案。

另外,另一种选择是 $(this).prev().prev().click();如果元素是静态的并且总是在相同的位置。

谢谢@Chandu。

【问题讨论】:

    标签: jquery file types input input-type-file


    【解决方案1】:

    你也可以使用 label 标签来模拟点击。 label 标签模拟当前表单的点击输入,id 类似于 for 属性。 示例:

    <label for="file-input">
        Click me!
        <input type="file" id="file-input" style="display:none;" />
    </label>
    

    【讨论】:

      【解决方案2】:
      <script type="text/javascript">
          $(function () {
              $('#btn-upload').click(function (e) {
                  e.preventDefault();
                  $('#file').click();
              });
          });
      </script>
      
      <style type="text/css">
          #file { display:none; } 
      </style>
      
      <div>
          <input type="file" id="file" name="file" />
          <button type="button" id="btn-upload">Image</button>
      </div>
      

      【讨论】:

        【解决方案3】:

        试试这个:

        $('.input-file > button').live('click',function() {
            $(this).closest('.input-file').find('input[type="file"]').click(); 
        });
        

        更新: 如果您使用的是 jquery >= 1.7,请将此版本与 on 一起使用:

        $('.input-file').on('click', 'button',function() {
            $(this).closest('.input-file').find('input[type="file"]').click(); 
        });
        

        【讨论】:

        • 就是这样!谢谢你。我还找到了另一个解决方案,我将在第一篇文章中发布。
        猜你喜欢
        • 2012-06-15
        • 2013-12-07
        • 2010-12-22
        • 2021-11-17
        • 1970-01-01
        • 1970-01-01
        • 2013-12-13
        • 1970-01-01
        • 2020-11-30
        相关资源
        最近更新 更多