0

I hava a simple jQuery script. I use .ajax() to get some info from my database, it works perfect.

The problem is the php-code genereate xhtml code with a-tags with different class, like .info, .delete and .edit.

I want to do stuff when i click in my .info link. I have tried this code:

$('a.info').click(function (e) {
    e.preventDefault(); 
    alert('Do stuff');
});

it dosen't work at all, nothin happens. firebug gives me no error so i dont know how to solve the problem.

    $('a').click(function (e) {
    e.preventDefault(); 
    alert('Do Stuff 2');
});

works on all links on the site but not on the link that is generated from the php code.

my code:

$(function(){       
$.ajax({
    type: "POST",
    url: 'users.php',
    data: 'getall=true',
    success: function( r ) { 
        $(' #content ').html( r );
    },
    error: function( ) {
        alert('Error');
    }
});

$('a.info').click(function (e) {
    e.preventDefault(); 
    alert('Do Stuff');
});


$('a').click(function (e) {
    e.preventDefault(); 
    alert('Do Stuff 2');
});

});

1
  • You should add the relevant snippet of generated markup - since that seems to be the root of the problem... Commented Feb 11, 2011 at 10:58

3 Answers 3

4

Use .live

$('a.info').live('click', function (e) {
    e.preventDefault(); 
    alert('Do stuff');
});


$('a').live('click', function (e) {
    e.preventDefault(); 
    alert('Do Stuff 2');
});
Sign up to request clarification or add additional context in comments.

1 Comment

I use this all the time for similar situation, it's extremely handy.
1

Use $.live. $.click registers the click events on objects that are currently present. Using $.live means your click events are basically re-registered when new elements are added to the page.

Comments

0

It looks like you're getting the HTML from the AJAX request. The click function will set up handlers for the objects that it knows about at the time you call - in this case, it is after the DOM is loaded but before the AJAX request is returned.

To handle the click event for any object that is added after the DOM is loaded, use the live function:

$('a.info').live('click', function (e) {
    e.preventDefault(); 
    alert('Do stuff');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.