2016-04-04 12 views
1

キャンセルボタンをクリックすると、最も近い「.myファイル」クラスを非表示にします。私は警告を取得し、キャンセルボタンが、隠れが動作していない上をクリックすると最も近いクラス/リンクタグを非表示

<div> 
    <label for="file">file</label> 
    <input type="file"> 
    <a href="#" class="my-file">first file</a> 
    <button class="cancel-button" type="button">Cancel</button> 
</div> 
<div> 
    <label for="file">file</label> 
    <input type="file"> 
    <a href="#" class="my-file">Second file</a> 
    <button class="cancel-button" type="button">Cancel</button> 
</div> 
$(function() { 
    $('.cancel-button').on('click', function() { 
     alert('works'); 
     $(this).closest('.my-file').hide(); 
     $(this).closest('a').hide(); 
    }) 
}) 

:私はこれをしようとしています。私はここで何が欠けていますか?

答えて

0

closest()は、親要素を見つけるために使用されます。 .my-fileは兄弟で.cancel-buttonなので、代わりにsiblings()を使用してください。

$('.cancel-button').on('click', function() { 
    $(this).siblings('.my-file').hide(); 
}); 

Working example

あなたは.my-fileはいつもあなたの代わりにprev()メソッドを使用することができ、あなたのHTML内.cancel-buttonの前に直接表示されることを保証することができる場合:

$(this).prev().hide(); 
0

closest()を見つけるために使用されます親エレメントを階層の上に置く代わりに、図のようにprev()を使用します。 -

$(function() { 
    $('.cancel-button').on('click', function() { 
     $(this).prev('a.my-file').hide();//OR $(this).prev().hide(); 
    }); 
}); 

DEMO