Reputation: 1641
I have a main PHP page that loads content in DIV's from an external file using JQuery and AJAX.
The page works as follows:
Each of the links in the DIV has parameters that filter results for the next DIV.
<div id="destination_Div01">
<a href="?Div01=1">Link</a>
</div>
$(document).ready(function() {
$('#Destination_Div01 a').click(function(){
$("#Destination_Div02").load("External.php"+$(this).attr('href')+" #Target_Div02");
return false;
});
$('#Destination_Div02 a').click(function(){
$("#Destination_Div03").load("External.php"+$(this).attr('href')+" #Target_Div03");
return false;
});
});
When the page is first loaded, only one DIV exists, when the new DIV is loaded, i don't think that JQuery notices that there is now a new DIV with links.
So now, when a link in the new Destination_Div02 is clicked, JQuery doesn't recognise the associated function and the browser continues to load the URL of the link. Instead what it is meant to do is use AJAX to pass the links URL parameters to the external PHP file, filter a recordset and return a new DIV.
How do get JQuery to function with the newly generated links?
Credit to "great_llama" Ensure you have JQuery 1.3+ and change code to $('#Destination_Div01 a').live("click", function(){
$(document).ready(function() {
$('#Destination_Div01 a').live("click", function(){
$("#Destination_Div02").load("External.php"+$(this).attr('href')+" #Target_Div02");
return false;
});
$('#Destination_Div02 a').live("click", function(){
$("#Destination_Div03").load("External.php"+$(this).attr('href')+" #Target_Div03");
return false;
});
});
Upvotes: 0
Views: 874
Reputation: 24754
I think the best solution is to use the callback parameter so after your dynamic content is loaded you can interact with its DOM.
$('#Destination_Div02 a').click(function(){
$("#Destination_Div03")
.load("External.php"+$(this).attr('href')+" #Target_Div03", null, function() {
$(this).click( ///your click code again/// );
//according to the docs this is the element you just loaded
);
return false;
});
Upvotes: 0
Reputation: 11739
With jQuery 1.3 came the ability to bind to future matching elements, using the .live method.
"Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events."
Upvotes: 2
Reputation: 10721
put your subsequent $('div').click() inside the callback function for each previous click:
$('div1').click(function(){
$('div2').load(link, data, function(){
$('div2').click(function(){
$('div3').load(link, data, function(){})
})
})
})
or you could give those links a class, and every time you add a new div, call a function that populates a list of links that have actions when clicked:
$('div1').click(function(){
$('div2').load(link, data, function(){
some_function();
}
});
function some_function(){
$('.class').click(function(){
//logic here
}
});
Upvotes: 0