简体   繁体   中英

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

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

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.

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM