开发者

jQuery scripts no longer run on partially refreshed elements

开发者 https://www.devze.com 2023-01-13 01:26 出处:网络
I have a number of jQuery scripts that select elements within the area that I run a partial page refresh on.

I have a number of jQuery scripts that select elements within the area that I run a partial page refresh on.

I am 开发者_运维技巧using this css tricks code snippet to refresh that part of the page:

$('#refreshbutton').click(function() {

 var url = "http://myUrl.com/indexTest.php?ID=" + Math.random(); 

 setTimeout(function() {
        $("#maindisplay").load(url+" #maindisplay>*","");
 }, 100); 
});

The problem is that the elements within #maindisplay are changed, thus are considered new elements in the dom. Since the scripts that select those elements and attach functions to them run at domready and not during the partial refresh, this poses a problem.

So far I have been unable to find a way to reattach the scripts to the elements within #maindisplay after I partially refresh it.

My question is: What is the optimal way to reattach the scripts to the refreshed area of the page.

Thank you for any advice.


You need to use the live() function to attach your click handler.


You have the following options that I can think of:

  • Put the attach in a function and call that function on page refresh
  • Use the .live() functionality
  • Use .delegate() functionality
  • Put the Javascript reference to the functionality in a reference in the refresh so that it executes as a part of that refresh
  • Put the function in the callback
  • make it part of your setTimeout
  • some other creative method I did not think of...

Just a note: I would look at the .delegate() with contextual selection added in recent versions (available in 1.4.2 for instance).


Does load() not take a callback function as it's second argument? Why not reattach event handlers to the elements with that function?

$('#result').load('ajax/test.html', function() {
  //reattach event handlers here.
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号