문제

I load a page with load () and then I create dinamically a

tag. Then I use live() to bind a click event and fires a function. At the end a call unload ().

The problem is that when I load the same page again ( without refresh ) when on click the function will be fired twice. If I exit again (again with unload ()) and load the page again on click will fire 3 times and so on .... A sample of my code is:

$('#tab').click(function() {
 $('#formWrap').load('newPage.php');
});
$('div').after('<p class="ctr" ></p>');
$('p.ctr').live('click', function(e) {
   if($(e.target).is('[k=lf]')) { console.log ('one'); delete ($this); }
   else if ....
});
function delete () {
  $.post( 'update.php',  data);
}

I have other $.post inside on this page and also on the above live fnc and all work well. The above one also works but like I said on the second load will fire twice and the 3 times and so on ... The weird part for me is that if replece the console with console.log ('two'); save the page and load the page without refresh it will fire on a different rows - one two -

if I unload the page replace the console with console.log ('three'); and load again will fire one two and three. I try to use:

$.ajax({ url: 'updateDB.php', data: data, type: 'POST', cache:false });

$.ajaxSetup ({ cache: false });

header("Cache-Control: no-cache");

none of this it's working. And I have this problem only on this fnc. What do you think, it could be the reason, it remembers it remembers the previous action and it fires again?

도움이 되었습니까?

해결책 2

in fact the answer belongs to @vittore.

I'll just try to explain a little better what was happening:

the live () fn was inside the page that I was loading. And on the first load () the live fn assigns the handler to click. BUT when you use unload and then remove all the elements from that page the connection between click and handlers remains.

And when I was loading again the same page (without refresh), the live function will keep the old handler and also attach the handler again, and so on every time load () it is used.

the trick it's to use die () before unload (). BUT one more thing to take in account: we can't use chaining with live() ($('div').children().live() will not work ) AND ALSO although:

$('.div .ctr').live() will work.

just calling $('.ctr').die() will not work.

So you have to use for both fn the same selector $('.ctr').live() and then $('.ctr').die()

maybe this will help someone. AND also check the new 1.4.2 delegate () and undelegate ()

다른 팁

I think you might have a typo by having ($this) vs $(this);
Also note that there is a delete operator in javascript so you might want to try another function name.
You might also be suffering from a cache somewhere (web servers by default set a cache for .js files)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top