Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery-单击按钮时,模拟输入[type=";file";]。仅在父元素中更改_Jquery_File_Types_Input_Input Type File - Fatal编程技术网

jQuery-单击按钮时,模拟输入[type=";file";]。仅在父元素中更改

jQuery-单击按钮时,模拟输入[type=";file";]。仅在父元素中更改,jquery,file,types,input,input-type-file,Jquery,File,Types,Input,Input Type File,我不确定标题是否正确地描述了我正在尝试做的事情,但我不知道如何命名这个问题 我试图使用css和jquery为输入[type=“file”]元素添加一些样式。这是我的密码: <div class="input-file"> <input type="file"><label>Select file...</label><button type="button">...</button> </div>

我不确定标题是否正确地描述了我正在尝试做的事情,但我不知道如何命名这个问题

我试图使用css和jquery为输入[type=“file”]元素添加一些样式。这是我的密码:

<div class="input-file">
    <input type="file"><label>Select file...</label><button type="button">...</button>
    </div>
若页面上只有1个元素,那个么它就可以正常工作,但若页面上有例如3个元素,每当我点击按钮1时,它就会启动函数3次。我希望它只对它的父元素

如何使用.parent或.before或任何函数来实现这一点

编辑:

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

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

谢谢@Chandu.

试试这个:

$('.input-file > button').live('click',function() {
    $(this).closest('.input-file').find('input[type="file"]').click(); 
});
更新: 如果您使用的是jquery>=1.7,则将此版本与一起使用:

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

$(函数(){
$(“#btn上载”)。单击(函数(e){
e、 预防默认值();
$(“#文件”)。单击();
});
});
#文件{显示:无;}
形象

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


点击我!

就是这样!非常感谢。我还找到了另一个解决方案,我将在第一篇文章中发布它。
$('.input-file').on('click', 'button',function() {
    $(this).closest('.input-file').find('input[type="file"]').click(); 
});
<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>
<label for="file-input">
    Click me!
    <input type="file" id="file-input" style="display:none;" />
</label>