开发者

Content pulled in via jQuery AJAX is not associating with previous functions

I'm using the jQuery .load()开发者_运维技巧 function to pull in data to populate a div with. The content I'm pulling in has CSS selectors that should match up with jQuery click functions I've written. However, when I load in the data, although the correct CSS selectors are there, when I click on areas that should invoke a response from jQuery, nothing happens.

Do I need to do some sort of reload?

Here's the code I've got for the jQuery AJAX:

$(document).ready(function() {
// AJAX functionality for drupal nodes
$(".ajax_node").click(function() {
    var ajax_src = $(this).attr("href"); // we're gonna load the href

    // empty target div and load in content
    // the space in the string before the #id is necessary
    $("#ajax_area").empty().load(ajax_src + " #ajax_wrapper");
    return false; // stops the link from following through
});

// General AJAX functionality
$(".ajax").click(function() {
    var ajax_src = $(this).attr("href");
    $("#ajax_area").empty().load(ajax_src);
    return false;
});
});


It's not working because you're essentially recreating the elements when you pull them in via load and you need to rebind the event handlers. I recommend using jQuery's live binding


Instead of this format:

$(".ajax_node").click(function() {

Use .live() for current and future elements, like this:

$(".ajax_node").live('click', function() {

The why: .live() listens for the event to bubble up at the DOM root, or document. It's a single event handler bound there...it doesn't matter when an element was added, they all bubble the click the same, when the click gets there: it checks the selector, if it matches it runs the handler.

Why your current method doesn't work: It's finding all the elements that match that selector at that time and binding the handler...new elements aren't there, so don't get that handler. You have 2 options to solve this, either use .live() which works in a different way, as described above, or re-bind the handler to that selector in the content of the request, like this:

function callback(data) { //your success callback, e.g. .load(url, callback)
  $(".ajax_node", data).click(myFunction);
}

In your case, I think .live() is much easier, you generally do the second with widgets and such, not strictly event handlers...but whatever floats your boat.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜