2016-04-19 154 views
0

我已經創建了一個表,並希望獲得一個ID點擊td。數據是通過ajax調用進行填充的,我希望在點擊刪除時使用id。所以它在飛行中添加了元素。在點擊無法正常工作jquery

$.ajax({ 
     url: 'http://localhost:8080/getUsers, 
     type: 'GET', 
     success: function (data, textStatus, jqXHR) { 
      $.each(data, function (index, result) { 
       $("<tr></tr>").attr("id",result.user_id+"userTr").appendTo("#userTBody"); 
       $("<td></td>").attr("id",result.user_id+"userName").appendTo("#"+result.user_id+"userTr"); 
       $("#"+result.user_id+"userName").html(result.username); 
       $("<td></td>").attr("id",result.user_id).appendTo("#"+result.user_id+"userTr"); 
       $("#"+result.user_id).html('Delete'); 
       $("#"+result.user_id).css('cursor', 'pointer'); 
       $("#"+result.user_id).addClass("delete"); 
      }); 
     }, 
     error: function() { 
      alert('err') 
     } 
    }); 

$('.delete').on('click', function() { 
     alert($(this).attr('id')); 
    }); 

我也嘗試過this.id但沒有任何反應。

+0

沒錯,閱讀帖子上面鏈接,你想切換您的符號從delete.on點擊document.on點擊「.delete」 –

+0

@Tushar,我有一個問題,爲什麼用文件.on代替簡單的$('delete')。on?由於在DOM中動態創建的元素? –

+1

@Java_NewBie請閱讀所述問題的答案。另請閱讀[事件代表團](https://learn.jquery.com/events/event-delegation/) – Tushar

回答

2

試試這個:

$(document).on('click', '.delete', function() { 
    alert($(this).attr('id')); 
}); 
+0

如果您無法在現有答案中添加任何內容,請不要回答這些明顯的複製問題,請將其關閉。 – Tushar