选择/更改文件时隐藏最近的类



假设我有以下html代码。

<div>
    <label>Test1</label>
    <input type="file">
    <a href="#" class="selected-file"></a>
</div>
<div>
    <label>Test2</label>
    <input type="file">
    <a href="#" class="selected-file"></a>
</div>
<div>
    <label>Test3</label>
    <input type="file">
    <a href="#" class="selected-file"></a>
</div>

我需要的是,如果有人更改/选择了一个文件,那么最近的<a>应该隐藏起来。我试着在下面做这样的事情

$(function() {
    $("input:file").change(function (){
        $(this).closest(".selected-file").hide()
    });
});

但这并没有隐藏<a>标签。我怎样才能做到这一点?

closest()用于查找与所提供选择器匹配的最近父元素。相反,由于ainput的兄弟,因此可以使用next():

$("input:file").change(function (){
    $(this).next(".selected-file").hide()
});

closest允许您选择父元素。您想要的是选择同级:

$(this).siblings(".selected-file").hide()

最新更新