jQuery的事件不触发动态创建的元素 [英] jQuery event not triggering on dynamically created element
问题描述
Here goes my question..
/ *我用ajax动态创建表* /
/* I am using ajax to dynamically create table */
$(".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);
});
});
在 $事件单击(离德尔)
不会自动触发我已经在控制台写事件则该事件开始正常工作的名称。是否与类名动态生成的任何问题,以及如何克服
the event click on $(".off-del")
is not triggering automatically I have to write in console the name of the event then this event starts functioning. Is there any issue with class name generating dynamically and how to overcome
After i wrote the name of the event in console it works
推荐答案
Ajax调用的是的异步的。
Ajax calls are asynchronous.
在元素通过AJAX追加,单击处理程序被注册,它找到 $没有元素(离德尔)
。
Before the elements are appended via ajax, the click handler gets registered, which find no elements with $(".off-del")
.
您也许应该使用 事件委派 。
You should probably use event delegation.
$(document).on('click','.off-del',function(){
alert('hello');
var id= $(this).closest('tr').find($(":first-child")).html();
console.log(id);
});
而不是 $(文件)
您可以使用一个静态的父母。
Instead of $(document)
you can use a static parent.
这篇关于jQuery的事件不触发动态创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!