Event handlers (except delegated events - more on this later) are bound directly to the element. If you replace that element - which is precisely what you do when you use the .replaceWith()
function - you're removing that event handler along with the element; you won't get your event bound to the new element.
The solution, as mentioned earlier, is event delegation. The general principle is that you set up an event handler on a static element that will contain your dynamic elements, which will handle the event and be responsible for executing the callback function when the target of the event matches the selector provided.
If you're using jQuery 1.7+, you can use the .on()
function to do this:
$(document).on('click', 'div[class^=locked_]', function(e) {
var newThis = $(this) ;
$(this).load(url + " #" + $(this).attr("id"), function() {
var loaded = $(this).children("#" + $(this).attr("id")) ;
alert($(loaded).attr("class")) ; // displays "locked_true"
$(newThis).replaceWith($(loaded)) ;
alert($(newThis).html()) ;
});
});
I've used document
in the example, but ideally you'd go for a more specific static element (the closer to your dynamic elements the better).
If you're not using jQuery 1.7+, you can get the same functionality using the .delegate()
function - the syntax is practically the same, you just switch the 'click'
and 'div[class^=locked_]'
arguments.