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.

Link to comment
Share on other sites

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");
	});
});

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.