jQuery事件不会触发动态创建的元素
这是我的问题..
/ *我使用ajax动态创建表* /
$(".n").click(function(){ var id= $(this).closest('tr').find('td.ide2').html(); //for displaying the table $.ajax({ type: 'POST', 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 = $(' ').appendTo($("#unique-list")); $(' ',{text:resp[i]}).appendTo(row); $(' ').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")
没有自动触发我必须在控制台中写入事件的名称,然后此事件开始运行。 类名生成动态以及如何克服是否存在任何问题
在我在控制台中写下事件的名称后,它可以工作
Ajax调用是异步的。
在通过ajax追加元素之前,点击处理程序被注册,它找不到带$(".off-del")
元素。
您应该使用事件委派 。
$(document).on('click','.off-del',function(){ alert('hello'); var id= $(this).closest('tr').find($(":first-child")).html(); console.log(id); });
您可以使用静态父级而不是$(document)
。
当您在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”元素的点击。
您正面临这个问题,因为在您动态创建的html之后,您还应该加载该事件,将其绑定到新创建的html。
因此,为事件创建一个函数,并在动态创建html后调用该函数。
虽然您可以使用事件委托 – 您也可以在添加所有HTML(在success
回调内) 后注册处理程序
for(var i=0;i<(resp.length);i++) { var row = $(' ').appendTo($("#unique-list")); $(' ',{text:resp[i]}).appendTo(row); $(' ').appendTo(row); }//end for loop $(".off-del").click(function(){ alert('hello'); var id= $(this).closest('tr').find($(":first-child")).html(); console.log(id); });