Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

jquery .live on load event

I need a way to use the jquery .live() function to act on elements that are loaded via ajax.

For instance a div is loaded via ajax .load()

<div id="mydiv"></div>

Normally I do .live() with a click event, but I need to know how to tell the dom that this new div has loaded without any explicit actions/events from the user.

This code doesn't work, but I want to do something like this:

mydiv = $("#mydiv");

mydiv.live("mydiv.length > 0", function() {
       // do something
});

The "mydiv.length" being a substitue for the typical "click" or other event.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another way to do this would be to use trigger() to trigger your own custom event (let's call it content_loaded). load() takes a callback function it calls on completion:

function callback_function(responseText, textStatus, XMLHttpRequest) {
    //if we have valid data ...
    trigger("content_loaded");
}

$("your_selector").load("your_url", callback_function);

And then just set up an event listener and run it whenever your event is fired.

$("your_selector").bind("content_loaded", your_results_loaded_function);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...