jQuery委托没有触发动态创建的表

我有以下代码驻留在我的.js文件中

//This is the row highlighting for the results table $(document).ready(function () { $("table").delegate('td', 'mouseover mouseleave', function (e) { if (e.type == 'mouseover') { $(this).parent().addClass("hover"); } else { $(this).parent().removeClass("hover"); } }); }); 

它基本上添加并删除表格行的样式。 这适用于创建运行时的表。

但是对于动态创建的表,它不会做任何事情。 这就是创建表的方式。

 //This function is called from the homepage, it calls for XML to be passed and renders the table with //Existing enquiries function loadEnqData() { //Display ajax load graphic showLoading('.enqLoading'); //Build results table, ready to receive results. $('.enqResults').append('
' + textlib.get('lblEnqDate') + '' + textlib.get('lblEnqUser') + '' + textlib.get('lblEnqClientName') + '' + textlib.get('lblEnqDetails') + '
'); //URL for XML data var strURL = "enqData.aspx"; if (debug) { $.jGrowl('url= ' + strURL); } //Ajax call $.ajax({ type: "GET", url: strURL, dataType: "xml", timeout: 30000, success: function (xml) { //process XML results for each xml node $(xml).find('row').each(function () { if (debug) { $.jGrowl('Returned id of ' + $(this).attr('id')); } //Set data variables var strEnqID = $.trim($(this).attr('id')); var strEnqDate = $.trim($(this).attr('DateTimeLogged')); var strEnqClient = $.trim($(this).attr('Client_Name')); var strEnqDetails = $.trim($(this).attr('Work_Details')); var strEnqUsername = $.trim($(this).attr('username')); //Add in a data row to the results table. $('#enqTable > tbody:last').append('' + strEnqDate + '' + strEnqUsername + '' + strEnqClient + '' + strEnqDetails + ''); }); //Tidy up $('.enqLoading').empty(); //Enable sorting $(document).ready(function () { $("#enqTable").tablesorter(); } ); //Catch errors }, error: function (XMLHttpRequest, textStatus, errorThrown) { $.jGrowl("Error Please contact IT support - " + XMLHttpRequest.responseText + " " + XMLHttpRequest.status + " " + textStatus + " " + errorThrown, { sticky: true }); } }); }

总而言之,此函数在我的enqResults div中创建一个新表,运行一个ajax查询,并使用此代码$(’#enqTable> tbody:last’)将行添加到表的tbody中。

为什么委托不能绑定到这些元素?

从代码的外观来看,您似乎也动态地附加了table元素 – 这就是问题所在。 delegate()方法的主要选择器必须是静态元素 – 即,在页面加载时以及页面的整个生命周期中存在的元素。

我可以看到你将你的表附加到.enqResults元素,记住这一点,试试这个:

 //This is the row highlighting for the results table $(document).ready(function () { $(".enqResults").delegate('table td', 'mouseover mouseleave', function (e) { if (e.type == 'mouseover') { $(this).parent().addClass("hover"); } else { $(this).parent().removeClass("hover"); } }); });