views:

67

answers:

4

I have added HTML to my page using the .after() method using HTML that is retrieved from a .GET() 'Ajax' call.

I have a button in my retrieved HTML and an event that is set to be triggered when this button is clicked. However the method that handles the .click event is never triggered. When I put the same button into my 'normal' html however the method is triggered and the .click() works fine.

This happens in both Mozilla and Firefox. What can I do to get the retrieved button to be recognised by jQuery? I have all my code within the $(document).ready(function() { ... will this have any affect?

+1  A: 

Sounds like you need to check out the .live() function.

http://docs.jquery.com/Events/live

Josh Sherman
+4  A: 

Use .live('click', fn) instead of .click(fn) to wire up your event handler. A regular .click(fn) wireup in $(document).ready() will only affect elements in the DOM during the initial page load.

Dave Ward
A: 

Try $("#btn").live("click", function(){...}) instead of $("#btn").click(function(){...})

Lloyd
A: 

If you have <script> tags contained in your data that you retrieve with .get() they will not be executed when added to the page with .after().

You can either attach the code after the fact:

$.get('/url', {key:value}, function(data){
     $("#wrapper").after(data);
     $("#new_id a").click(function(){ ... });
}, 'html');

Or you can parse the return data for <script> blocks and eval() them after you have used the .after() function. Be very careful you trust the <script> blocks before you blindly eval them.

Doug Neiner