How can I load dynamic content with jQuery?
I'm following "How to Load In and Animate Content with jQuery" and everything works fine, but if I have other links in the loaded <div/>
the script doesn't work. Can anyone spot the bug in the following code?
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('.nav li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+'.html #content';
$('#content').load(toLoad)
}
});
$('.nav li a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('fast',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').show('normal',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
});开发者_如何转开发
My scenario
- start from site index
- click 'contact'
- contact 'content div' is loaded
- in contact content div I have other link 'map.html' I want open it that same at other, only 'content div' loading --> and it don't work - site is loading normal
If the link in the content you are talking about is the .nav li a
link, then the problem here is that the .click
event is only assigned once (on documentready) and does not affect content loaded after documentready.
So the easiest way would be changing $('.nav li a').click(function(){
to
$('.nav li a').on('click', function(){
With this the event handler will be attached to content loaded later as well.
Note: Depending on your jQuery version you may have to use a different method for this .live behaviour:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
精彩评论