views:

210

answers:

4

I'm placing content on my page through an ajax (post) request like so:

$("input#ViewMore").click(function() {
      var data = { before: oldestDate, threadId: 1 };
      $.post("/Message/More", data,function(html) {
       $('tbody#posts').prepend(html);
       return false;
      },
      "html");
      return false;
     });

with the html coming back looking something like:

Message output Quote

This is all working fine and dandy, everything appears as it should, no problems.

The problem occurs when I have an event hooked into the "quote" anchor that has been added through the ajax call. Specifically, a jQuery event on that anchor does not fire. Why?

For instance:

$("#quote).click(function() { ... });

Does nothing. Acts like there is no event on it. I know it is working on other anchors on the page that were not added through a ajax request, so there is not a code error there, plus if I refresh the page it will then fire correctly. Is there some reason that this is happening, do I need someway to reinitialize that event on the anchor tag somehow? Any ideas?

Working with jQuery 1.3.1 (didn't work with 1.2.6 either) so I believe it is my implementation not code itself.

+2  A: 

When the new content is added to the page with Ajax you have to re-register all the events to those new elements.

Luca Matteis
how would I go about doing that?
rball
I'll look on google...hopefully something there...
rball
+3  A: 

You can use Events/live of jQuery 1.3, live will bind a handler to an event for all current - and future - matched elements.

CMS
Ok, I'll give that a go.
rball
Nevermind that did work, thanks!
rball
A: 

Changed to

$('#quote').live("click", function() { ... }

and

$("input#ViewMore").live("click", function() { ... }

Doesn't seem to work

rball
A: 

CMS's answer helped, but here's how it ended up:

The view more button event remained the same as it was outside of the AJAH request that added it:

$("input#ViewMore").click( function() { ... }

Elements that had events that were being added in and out of the AJAH request needed to use the live method:

$('#quote').live("click", function() { ... }

Works like a charm!

rball