2016-04-13 24 views
1

動的に作成された要素にトリガーを設定し、イベントの抽出を使用してイベントを取得し、動的要素を削除する必要があります。動的に作成された要素にカスタムトリガーを追加する

<div class="row"> 
    <div class="col-md-8 clickable"></div> 
    <div class="col-md-4 display-clicks"> 
     <ul class="clicks"> 
     </ul> 
    </div> 
</div> 

ので、我々は表示-クリック内で上記のHTMLを持ってULはクリック可能なdiv要素とそれぞれの横にある[削除]ボタンでクリックした座標のリストに追加されDIV言うことができます。クリック可能なdivには、動的に作成されたスパンがすべて挿入されます。これらのスパンのすべては、クリックの連結された座標である一意のIDを持ちます。

$('.display-clicks').on('click','button',function(){ 
     // and this gets me the id of the dynamic span to be removed 
     // from the clickable div 
     var id = $(this).data('span-id'); 

     // this wont work 
     $(id+'_span').remove(); 

     // neither will this 
     $(id+'_span').trigger('myEvent'); 

     $(this).parent().remove(); 
     console.log(id); 
    }) 

myEventこの

$('.clickable').on('myEvent', 'span', function(event){ 
     $(this).remove(); 
    }) 

任意のアイデアのようになります。私は使用して座標やボタンを含む追加のLiを削除することができますか?

+1

'$( 'クリック可能な'

$('.clickable').on('myEvent', 'span', function(event){ $(this).remove(); }) 

とあなたの関数は、このようなものですが)=> $( '。clickable') ' –

+0

はい、申し訳ありませんが、ちょうどtypo .clickableが実際のコードにあります – futureweb

+0

動的に追加される' html'好き? –

答えて

1

$(this).parent().remove(); も親を削除するので、this要素も削除されます。したがって、idを定義することはできず、スパンを選択することはできません。その行をブロックの最後に置く。また、あなたのIDは数字で始めることはできません - http://www.w3schools.com/tags/att_global_id.asp

+0

のようなidを持つちょうどそのスパンです。私は実際にidを変数にキャストしてから親を削除することができます。スパンとリを削除するために私は質問コードを編集します。 – futureweb

+0

また、 'id'値の先頭に数字を使用しないで、最初の文字の後に使用することができます。文字は –

+0

でなければなりません。私のコードは生き生きしていますが、 – futureweb

0

はこのお試しください:

$('.display-clicks').on('click','ul',function(){ 
     $(this).parent().remove(); 
     // and this gets me the id of the dynamic span to be removed 
     // from the clickable div 
     var id = $(this).data('span-id'); 

     // this works now 
     $("#" + id+'_span_just_remove').remove(); 

     // this works too 
     $("#" + id +'_span_trigger').trigger('myEvent'); 
    }) 

Plunker:https://plnkr.co/edit/ocZv95B3wBifX5zK7ob4?p=preview