jQuery 事件未在动态创建的元素上触发

Rag*_*san 3 javascript ajax jquery

这是我的问题.. 在此输入图像描述

/* 我正在使用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);
          });
        });
Run Code Online (Sandbox Code Playgroud)

单击的事件$(".off-del")不会自动触发我必须在控制台中写入事件的名称,然后该事件开始运行。动态生成类名是否存在问题以及如何克服

当我在控制台中写下事件的名称后,它就可以工作了在此输入图像描述

Sha*_*k D 6

Ajax 调用异步的。

在通过 ajax 附加元素之前,会注册单击处理程序,该处理程序找不到带有$(".off-del").

您可能应该使用事件委托

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

$(document)您可以使用静态父级来代替。