开发者

JQUERY: (selector).load(url id), loads every second click

开发者 https://www.devze.com 2023-04-09 06:22 出处:网络
I wanted to not reload the page every click of a sub-gallery. So I decided to .load the content in to the wrapper div of the page.

I wanted to not reload the page every click of a sub-gallery.

So I decided to .load the content in to the wrapper div of the page.

The content works and does change on first click without a refresh, but the second click does a reload and so on alternately..

I'm guessing the script doesn't know about the new content?

I used Jquery's .bind on the click event, the click event always fires without a page refresh. I tested this by commenting out the .load line and using a alert("wonga!");

It's the .load that causes the page refresh on the second click, not sure why though.

If anyone has any suggestions or advice about this, I will be most grateful.

$('#gallery_subgalleries a').bind('click', function() {
      $('.content_loader').load("index.cfm?subgallery_id=" + $(this).attr('rel') + "&gallery_id=" + $(this).attr('gallery_id') + " " + ".content_loader");
return false;
});

The script executes at the bottom of the page:

 <div class="content_loader">
     <!--- page content --->
     <div id="gallery_subgalleries">
          <a href=""  gallery_id="" rel="">sub gallery name</a>
     </div>
     <!--- page content --->
 </div>

 <script>is here</script>

I am unable t开发者_JAVA百科o show the page source at this time..

Thanks for any help.


When you bring in new content, the new link element it contains won't fire the load() call. The reason for this is that the new link element didn't exist when you did the original bind().

There are two ways around this.

You can either rebind the new links everytime you do a load i.e. rerun the snippet you have above.

The other better way is to use event delegation, which uses another element to listen for the clicks and doesn't require any rebinding. It's also super neat, you would only have to make one change to your code:

$('#gallery_subgalleries a').live('click', function() {
    $('.content_loader').load("index.cfm?subgallery_id=" + $(this).attr('rel') + "&gallery_id=" + $(this).attr('gallery_id') + " " + ".content_loader");
    return false;
});

Note the change from bind to live.

0

精彩评论

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