关于动态加载内容的jquery事件

我试图在一些动态加载的内容上添加一个click事件,我有这个:

$("#dailyCount table thead th").each(function(){ var yd = "#" + $(this).attr("id"); $(document).on("click", yd, function(){ alert("a"); }); }); 

元素id从1到当月的最后一天。 有任何想法吗 ?

您可以将一个委托用于从选择器返回的所有元素,而不是为每个元素添加委托处理程序。

所以尝试:

 $(document).on("click", "#dailyCount table thead th", function(){ alert("a"); }); 

演示: http : //jsfiddle.net/agLBm/

尝试使用动态检索的id委托事件与尝试将事件附加到动态元素本身相同。

因此,要么将ur代码放在document.ready函数中,要么硬编码动态元素的id。

试试这个:

 $(document).on("click", "#dailyCount table thead th", function(){ alert("a"); }); 

虽然,如果我是你,我会用选择器摆脱DOM。 只需在表格中的TH元素中添加一些类,然后选择“em”。

 
Whatever
$(document).on("click", ".dailyCount-table-headCell", function () { console.log("a"); });

它允许您在不更改JS的情况下更改标记。 好像你需要做网格而不是表格。

假设您将在代码中进一步使用id,请尝试以下操作:

 $("#dailyCount table thead th").on("click", function(){ var id = $(this).attr('id'); // id will now have the id of clicked element. alert("a"); }); 

希望这可以帮助。