Jump to content

Do jQuery selectors work with AJAX content?


Guest

Recommended Posts

This works:

 

<script type="text/JavaScript">
$(document).ready(function() {
	$("a.test").click(function() {
		// Do something
		alert("test");
	});
});
</script>
<div id="wrapper">
<a class="test">test</a>
</div>

 

BUT when the content of #wrapper is returned from my AJAX function, it no longer works:

 

<script type="text/JavaScript">
$(document).ready(function() {
	loadReviews();
	$("a.test").click(function() {
		// Do something
		alert("test");
	});
});
function loadReviews() {
	$.post("backend.php", {}, function(xml) {
		displayReviews(xml);
	});
}
function displayReviews(xml) {
	$("#wrapper").empty();
	$("review", xml).each(function(id) {
		review = $("review", xml).get(id);
		$("#wrapper").prepend(
			"<a class=\"test\">test</a>\n"
		);
	});
}
</script>
<div id="wrapper">
 
</div>

 

Please keep in mind the AJAX function works fine. It's the jQuery selector that doesn't seem to be working once the content is returned from the AJAX function.

You have to bind the click function to the live function when you have dynamic elements on your page.

 

For instance, for your second example you would do this for the click part

$(document).ready(function() {
	loadReviews();
	$("a.test").live('click', function() {
		// Do something
		alert("test");
	});
});

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.