2016-11-04 9 views
-1

私は次のコードを持っていますが、親divが削除するボタンをクリックするとどうすれば実現できますか?Jquery onlick親divを削除

 function removeDiv(){ 
 
      $(this).parent('div').remove(); 
 
     }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    <div> 
 
     <div> 
 
      <div><button onClick="removeDiv()">button1</button></div> 
 
     </div> 
 
     <div> 
 
      <div><button onClick="removeDiv()">button2</button></div> 
 
     </div> 
 
    </div>

+2

'のonClick = "removeDiv(この)"'と '関数removeDiv(ELEM){ $(ELEM).parent( 'DIV')(削除)。 } ' – Satpal

答えて

1

removeDiv関数に現在の要素のコンテキストthisを渡します。

function removeDiv(elem){ 
    $(elem).parent('div').remove(); 
} 

として

<div><button onClick="removeDiv(this)"></button></div> 

変更機能あなたはjQueryのを使用しているようしかし、あなたはそれを使用してイベントをバインドする必要があり、ここで私は要素にイベントハンドラをバインドするためにClass Selector (“.class”)を使用している例であり、 。 jqueryを使用して

jQuery(function($) { 
 
    $('.removeDiv').on('click', function() { 
 
    $(this).parent('div').remove(); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <div> 
 
    <div> 
 
     <button class="removeDiv">removeDiv</button> 
 
    </div> 
 
    </div> 
 
    <div> 
 
    <div> 
 
     <button class="removeDiv">removeDiv</button> 
 
    </div> 
 
    </div> 
 
</div>

0

単にクリックイベントを追加:

1.$(this).parent('div').remove(); 

    2.$(this).closest('div').remove(); 
:blew.Itsのような は closest parent div

2つのメソッドが削除されます

$(document).ready(function(){ 
 
$('button').click(function(){ 
 
     $(this).parent('div').remove(); 
 
    //$(this).closest('div').remove(); its also working 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <div> 
 
     <div><button >remove1</button></div> 
 
    </div> 
 
    <div> 
 
     <div><button >remove2</button></div> 
 
    </div> 
 
</div>

関連する問題