2015-09-01 99 views
1

這裏不用我的問題.. enter image description herejQuery的事件動態創建的元素上不觸發

/*我使用AJAX動態創建表*/

$(".n").click(function(){ 
     var id= $(this).closest('tr').find('td.ide2').html(); 

     //for displaying the table 
     $.ajax({ 
      type: 'POST', 
      url: '<?php echo base_url(); ?>Admin/show', //We are going to make the request to the method "list_dropdown" in the match controller 
      dataType:'json', 
      data: {'id':id}, //POST parameter to be sent with the tournament id 
      success: function(resp) { 

      for(var i=0;i<(resp.length);i++) 
       { 
       var row = $('<tr></tr>').appendTo($("#unique-list")); 

       $('<td />',{text:resp[i]}).appendTo(row); 
       $('<td class="off-del glyphicon glyphicon-minus"></td>').appendTo(row); 

      }//end for loop 
      } //end success 
      }); //end ajax 




      $(".off-del").click(function(){ 
      alert('hello'); 
      var id= $(this).closest('tr').find($(":first-child")).html(); 
      console.log(id); 
      }); 
     }); 

$(".off-del")事件點擊也不會觸發自動我必須在控制檯中寫入事件的名稱,然後此事件開始運行。是否有與類名動態生成,以及如何克服

後,我在控制檯寫了事件的名稱它的工作原理enter image description here

+0

使用事件委託後 – Ejaz

回答

3

Ajax調用異步的。

之前的元素通過AJAX追加,單擊處理程序被註冊,其中找到$(".off-del")沒有元素。

您應該使用event delegation

$(document).on('click','.off-del',function(){ 
    alert('hello'); 
    var id= $(this).closest('tr').find($(":first-child")).html(); 
    console.log(id); 
}); 

而不是$(document)您可以使用靜態父級。

1

當您設置在jQuery的像這樣的事件處理程序的任何問題:

 $(".off-del").click(function(){ 
     alert('hello'); 
     var id= $(this).closest('tr').find($(":first-child")).html(); 
     console.log(id); 
     }); 

你告訴它去查找文檔與類元素「關-DEL」就在那一刻。你的ajax操作會添加這樣的元素,但它只會在你嘗試設置處理程序之後纔會發生。

取而代之的是,你可以設置處理程序的文檔對象上,並利用事件冒泡的:

$(document).on("click", ".off-del", function() { 
     alert('hello'); 
     var id= $(this).closest('tr').find($(":first-child")).html(); 
     console.log(id); 
}); 

您可以設置事件處理程序的方式你想要的任何時候,它會處理來自任何時候添加的任何「.off-del」元素的點擊。

0

您都面臨這個問題,因爲你的後動態創建的HTML,你也應該加載,將其綁定到新創建的HTML事件。

因此,創建一個事件函數並在動態創建html之後調用該函數。

0

雖然你可以使用事件代表團這一點 - 你也可以只登記處理你附加的所有HTML(該success回調內部)

for(var i=0;i<(resp.length);i++) { 
    var row = $('<tr></tr>').appendTo($("#unique-list")); 
    $('<td />',{text:resp[i]}).appendTo(row); 
    $('<td class="off-del glyphicon glyphicon-minus"></td>').appendTo(row); 
}//end for loop 

$(".off-del").click(function(){ 
     alert('hello'); 
     var id= $(this).closest('tr').find($(":first-child")).html(); 
     console.log(id); 
}); 
相關問題