Jquery how to select and use ajax loaded elements
I use ajax to load a page (example.html). I've got two buttons: one for ajax load function and another to act on loaded content. But it doesn't react. I 开发者_运维问答tried to use:
$(document).ready(function(){
$("#load")
.click(function(){
$("content").load("example.html");
});
$("#example_content").load(function(){
// some actions to loaded page
});
the jQuery load function does not work like and event hook function, so the second .load call will expect to receive a url-like string to make a new request to the server to get more data (link http://api.jquery.com/load/).
If you want to do something with the content that was loaded into the div, I'd suggest you use the ajax method, which could be used like this:
$.ajax({
//where is the data comming form? url
url : "example.html",
//what happens when the load was completed? the success function is called
success : function(data){
//add the content from the html to the div
$("content").html(data.responseText);
//do whatever else I want with the content that was just added to 'content'
console.debug($('content')); // should show you all the html
// content written into that element
//my content specific funciton
myFunction();
}
});
If you want to shorter way, using the $.get(url, success) function should help you, but this uses $.ajax inside, so you're better off using directly $.ajax.
Recap:
1) .load is a function that uses .get to fetch content. http://api.jquery.com/load/
2) .get has a success function, which writes the content received from the given url to the target element. http://api.jquery.com/jQuery.get/
3) .get is a function .ajax, which is the core of the jQuery ajax functionality. http://api.jquery.com/jQuery.ajax/
精彩评论