9

Being fairly new to jQuery and the AJAX basics, I've been trying to set up some fairly simple dynamic loading.

I include a .js file setting up the click event handler, and it looks like this:

var baseurl = document.getElementById("baseurl").getAttribute("href");
var pattern = new RegExp("[^/]+");
var page = "cnt/" + pattern.exec(window.location.href.substr(baseurl.length)) + ".php";

$(document).ready(function(){
    $('a.ajax').bind('click',function(event){
        event.preventDefault();
        $('#content').load("cnt/" + pattern.exec(this.href.substr(baseurl.length)) + ".php")
    })
});

Note that I do some changes to the file so the relative href "testing/" would turn into an absolute path to the file "cnt/testing.php".

My anchor tags look like this:

<a href="testing/" class="ajax">Link to testing page</a>

My problem is, that whenever new content is loaded into div#content the handler in my .js file is not registered for any links that may have appeared using AJAX. In other words the links will simply act as ordinary anchor-tags. I want it to load the next page using AJAX, just like it does with the first page.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Steen Schütt
  • 1,355
  • 1
  • 17
  • 31

2 Answers2

12

If you're inserting new content, that content would be dynamic, and the event handler can only be bound to elements that actually exist. You need to delegate the event to an element higher in the DOM that exists at the time you are attaching the event handler. I'll use the document, you'll use the closest non dynamic parent to delegate to :

$(document).on('click', '.ajax', function(event){
    event.preventDefault();
    $('#content').load("cnt/" + pattern.exec(this.href.substr(baseurl.length)) + ".php")
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    Hmm, would've been useful if the .bind documentation mentioned that. – Steen Schütt Dec 11 '12 at 14:57
  • 2
    If you look at the `bind()` docs, all the way at the top, it says, `on()` is now the preferred method, and in the docs for `on()`, it's explained in detail :) .. – adeneo Dec 11 '12 at 15:35
1

using $('a.ajax').live('click', stuff here) will handle all links with class "ajax" whenever they happen to be added.

Randy Hall
  • 7,716
  • 16
  • 73
  • 151
  • 2
    This answer isn't technically *wrong*, but... "*As of jQuery 1.7, the [`.live()`](http://api.jquery.com/live/) method is deprecated. Use `.on()` to attach event handlers. Users of older versions of jQuery should use `.delegate()` in preference to `.live()`.*" (from the [`.live`](http://api.jquery.com/live/) docs page) – apsillers Dec 11 '12 at 14:52
  • 1
    @apsillers Really? Geeze, I need to brush up on jQuery. Been too long in the native. – Randy Hall Dec 11 '12 at 14:53