jQuery事件不会触发动态创建的元素

时间:2015-09-01 16:23:07

标签: javascript jquery ajax

这是我的问题.. enter image description here

/ *我使用ajax动态创建表* /

D = dat[-1]

事件点击 $(".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); }); }); 没有自动触发我必须在控制台中写入事件的名称然后此事件开始运行。是否存在动态生成类名以及如何克服

的问题

在我在控制台中写下事件的名称之后,enter image description here

4 个答案:

答案 0 :(得分: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 :(得分:1)

在jQuery中设置事件处理程序时,如下所示:

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

你告诉它在那一刻中找到文档中带有“off-del”类的元素。您的ajax操作将添加此类元素,但只有在您尝试设置处理程序后才会发生。

而不是那样,您可以在文档对象上设置处理程序并利用事件冒泡:

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

您可以随时设置事件处理程序,并且可以随时处理来自任何“.off-del”元素的点击。

答案 2 :(得分:0)

您正面临这个问题,因为在动态创建的html之后,您还应该加载该事件,将其绑定到新创建的html。

因此,为事件创建一个函数,并在动态创建html后调用该函数。

答案 3 :(得分: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);
});