Reusing jQuery selectors and actions after programmatically inserting new content

JQuery hackers, hello :-)

Let's assume you have the following code:

$('.links').click(function(){
    //Do something
}

      

And then I insert dynamic content into the HTML DIV content (say, for example, after clicking the button, new content is added). This content has the class "links". The problem is that the "click" button is not registering in the newly inserted content.

How to tell JQuery to reselect all items with the word "links" and apply the above function to them? Could this be automated?

Thank.

+2


source to share


1 answer


You want to use event delegation:

$('.links').live("click",function(){
    //Do something
});

      

This will prevent you from losing dynamically inserted class elements links

from losing your click event handler. Note that you will also need jQuery 1.3 or later for this . See Events / live .

Another way is to re-bind using a callback of whatever jQuery ajax method you choose, for example:



$('#someDiv').load('page.html', function() {
    $('.links').click(function(){
        //Do something
    });
});

      

or more neat:

function initLinks() {
    $('.links').click(function(){
        //Do something
    }
}

$('#someDiv').load('page.html',initLinks);

      

+10


source







All Articles