开发者

Ajax problems when loading into a div. Jquery

开发者 https://www.devze.com 2023-02-14 06:41 出处:网络
I am not so good on javascript, and I am trying to load some images开发者_如何学Go into a div, via an external html page, with some opacity function in jquery. Is there a simple function that will re

I am not so good on javascript, and I am trying to load some images开发者_如何学Go into a div, via an external html page, with some opacity function in jquery. Is there a simple function that will re apply the scripts needed once the ajax call has been made. I have seen jquery live, but before I start tearing my hair out, I wondered if I was on the right tracks. Or is there a really simple method I am missing.


Yes, live and delegate are your friends.

Specifically, you should try to use delegate, because events bound with live bubble up all the way up the DOM before they're caught.

The syntax for delegate is:

$("#parent_element").delegate(
    "#child_selector_event_occurs_on", 
    "click" // <-- Event to declare a handler for
    function() { ... });

The linked documentation page for delegate has some examples.

Edit:

My answer above assumes that you're losing event handlers that are bound to content that's being replaced or updated with AJAX. If you need to do things like re-initialize widgets or run other custom code, you'd benefit by moving that code into a common function and calling it upon a successful load of new content (and in your document.ready handler).

For example:

function init() {
    /* Write initialization code here */
}

$(document).ready(function() { init(); });

/* Later on, when you reload the content: */
$("#ajaxified").load("foo.html", function() { init(); });

Another alternative is the livequery plugin, which I haven't used but I've heard good things about. Specifically, you'd be looking at the helper function functionality:

$('#selector') 
    .livequery(function(){ 
        /* Write code here to execute when a new element matching the 
           selector is added. */
        init();
    });
0

精彩评论

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

关注公众号