问题描述:

Because I use ajax I've wrote script for image upload button using 'live'

$('.image_upload').live('click',function()

This brings up some dialog, u can upload image , etc ,etc. everything works fine.

Now the problem comes if I press home on my site so new data is put into the div where image upload button was. And I see home screen. Now I can go again to image upload page and see it. Now lets again hit home, so div where image upload button was will be filled with new data representing home screen. Now let's go back and press the image upload button. And what you know ? button press live script will perform 3 times. Like there was 3 buttons at the same place. Like old data was still there in div. How can I solve this problem ?

Is there any kind of command which can force jquery to forget old data?

MORE DETAILS.

My ajax looks like this....

<div>some header with menu buttons'HOME' , 'ADD image'</div>

<div>HERE is content</div>

Now If u press home in content div u see only home data.

If u press Add image u see add_image button + script $('.image_upload').live('click',function() also loads into content div.

Now if u press home again , again only home data will be loaded inside content div which means that probably old data is deleted.

But if u play with home/add image buttons several times and then press upload image button inside content div. Script acts several times. as if script is written there several times, or button is rendered there several times.

UPDATE

I've figured out that problem is with script which is loaded into the div with image_upload button itself.

If I put the script somewhere in static footer, which is untouched and is static, so in content div only html is changing, then everything works OK.

Question is WHY script is not deleted if u put it inside content div ? Because If u change the html of div with new data it must be deleted with old html am I right ?

网友答案:

Using .live registers the events on the document rather than the element. So even though the element was replaced the event still existed and each time you ran the code another event was registered.

You can use .die to remove events, or as you found, make sure you only bind live events once.

$('.image_upload').die('click'); // Will remove click events registered with live
相关阅读:
Top