I have the following code that resides in my .js file
//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");
}
});
});
It basically adds and removes a style to a table row.
This works perfectly for tables that are created are runtime.
However for tables that are dynamically created it doesn’t do a thing.
This is how a table is being created.
//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('<table id="enqTable" class="enqTable"><thead><tr><th>' + textlib.get('lblEnqDate') + '</th><th>' + textlib.get('lblEnqUser') + '</th><th>' + textlib.get('lblEnqClientName') + '</th><th>' + textlib.get('lblEnqDetails') + '</th></tr></thead><tbody></tbody></table>');
//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('<tr onclick="selectEnq(\'' + strEnqID + '\');"><td>' + strEnqDate + '</td><td>' + strEnqUsername + '</td><td>' + strEnqClient + '</td><td>' + strEnqDetails + '</td></tr>');
});
//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 });
}
});
}
To summarise, this function creates a new table in my enqResults div, runs an ajax query, and adds rows to the tbody of the table with this code
$(‘#enqTable > tbody:last’).append
Why can delegate not bind to these elements?
From the looks of your code it appears you are appending the
tableelement dynamically too – this is the problem. The primary selector of thedelegate()method must be a static element – ie, one that is present on page load, and for the entire life of the page.I can see you are appending your table to the
.enqResultselement, with that in mind, try this: