Alon
Alon

Reputation: 7758

How to delete and reload jQuery / javascript functions after ajax call

Let's say I have this code:

<div id="content">
</div>

and I use a simple ajax request to fill the content with data which work when I click some button

    $.get("page?num=" + pageNumber, function(data){
                $("div#content").html(data);
});

one time the data will be

<div id="Data1">
</div>

and other time it will be

<div id="Data2">
</div>

for each id I have differnet jquery functions. for exampe:

$('#Data1').click(function(){});

some of the functions are similar and some are different.

My question - if I click the button I load all the scripts I need. when I click the other button I need to load the scripts again for the new content, but what happens to the old functions that was relevant to the previous content? Each time I click I load new scripts without deleting the last ones.

How do I delete/manage my scripts correctly?

thanks, Alon

Upvotes: 0

Views: 2314

Answers (4)

dku.rajkumar
dku.rajkumar

Reputation: 18568

I am not sure if i understood your question. are you expecting something like

$("div#content").html(""); // deleting existing data
$("div#content").html(new_data); //loading new data

Upvotes: 1

Jos&#233;
Jos&#233;

Reputation: 391

Gurung is right about the event handler, but as of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers instead.

(I could not post this information as a comment, so it had to be a new answer, sorry aboyt that).

Upvotes: 1

Tony Bogdanov
Tony Bogdanov

Reputation: 7686

jQuery binds events to DOM objects (divs) in this case when they are called. Which means it looks for an element with the given ID and then binds it. Since Edit1 and Edit2 does not exists when the script is run, they are not bound.

You can try to bind them each time you change their ID.

function rebind() {
    $('#content').click(function(){});
    $('#Data1').click(function(){});
    $('#Data2').click(function(){});
}

Call this whenever you load new content in the div.

Upvotes: 1

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

May should just use the .live() function.

Description: Attach an event handler for all elements which match the current selector, now and in the future.

Upvotes: 0

Related Questions