Reputation: 57
I have a table I manipulate with jQuery, like so: https://jsfiddle.net/tuurester/eow3x2w5/ That part is all fine and working as it's supposed to.
I add that table to a page via via jQuery's load
function, like so:
$('#matrixclicker').click(function(){
$('#matrixwrapper').load('matrix.php');
}
$('#matrix-table').on("click", ".matrix-table-chooser", function() {
$(this).removeClass('matrix-table-chooser');
$(this).addClass('matrix-table-chosen');
});
$('#matrix-table').on("click", ".matrix-table-chosen", function() {
$(this).removeClass('matrix-table-chosen');
$(this).addClass('matrix-table-chooser');
});
The table loads to the page with no problems, but I can no longer manipulate it using jQuery, i.e. the functionality to change the cells' class values works no more. After reading a plethora of related questions here on stackoverflow, I was under the impression that using on("click", function())
would do the trick, but it doesn't seem to.
What am I missing?
Upvotes: 1
Views: 30
Reputation: 337590
You're using delegated event handler, which is correct, however the primary selector needs to be an element available in the DOM when the page loads. This is why selecting the table doesn't work; it's appended to the DOM after you attempt to add the event handlers.
To fix this, change the selector to be the #matrixwrapper
instead. Also note that you can join both event handlers together and use toggleClass()
to simplify the logic.
$('#matrixwrapper').on("click", ".matrix-table-chooser, .matrix-table-chosen", function() {
$(this).toggleClass('matrix-table-chooser matrix-table-chosen');
});
Upvotes: 1