2016-04-13 26 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 DIV該UI被附加了座標列表中點擊可點擊股利和旁邊的每個一個刪除按鈕。可點擊的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(); 
    }) 

任何想法?

+1

'$( '點擊' )=> $('。clickable')' –

+0

是啊對不起,這只是一個錯字.clickable是在真實的代碼 – futureweb

+0

什麼動態附加'HTML'看起來喜歡? –

回答

1

$(this).parent().remove(); 也會刪除this元素,因爲您要刪除它的父級。因此無法定義id,您無法選擇您的跨度。將該行放在塊的末尾。另外你的ID不能以數字開頭 - http://www.w3schools.com/tags/att_global_id.asp

+0

我可以看到它看起來這樣我實際上將id轉換爲一個變量之前刪除父母,我可以console.log它後嘗試刪除span和li我將編輯問題代碼。 – futureweb

+0

也不要在'id'的值開頭使用數字,你可以在第一個字符之後使用它們 - 應該是一個字母 –

+0

非常奇怪我的代碼似乎能正常工作,但不在我的開發機器上對不起 – futureweb

0

試試這個:

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

,你的功能是這樣的:

$('.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

相關問題