The problem: Links in dynamically loaded pages aren't loading other pages dynamically.
On my index page I have links like the following:
<li><a class="page_one" title="page_one" href="page_one.html">Page One</a></li>
<li><a class="page_two" title="page_two" href="page_two.html">Page Two</a></li>
These dynamically load the content within <div id="guts">
from the external pages into a div with the same id on the index page using the script dynamicpage.js (below), unless javascript is off, then it will simply load the external pages normally.
Here's the javascript:
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
$el;
$(".dyn").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " #guts", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
});
});
$(".dyn a").removeClass("current");
$(".dyn a[href="+newHash+"]").addClass("current");
});
});
};
});
$(window).trigger('hashchange');
});
The links on the index page are working great but for instance if I wanted to link to page_2.html from the dynamically loaded page_1.html, page_2 is being loaded normally and not updating the url to /#page_2.html
I've tried changing .delegate to .live, but this stops it working altogether.
Could anyone push me in the right direction?
Thanks in advance!
Try this instead:
$("#main-content").delegate(".dyn a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
Here's why: your function
$(".dyn").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
binds click
handlers correctly on exiting and new <a>
elements within the matched .dyn
elements. So if you were to add new <a>
tags to the .dyn
elements, the script would work as intended.
However, the $mainContent.hide().load(...
method replaces the contents of $("#mai-content")
with newly loaded content, meaning you've replaced the original $(".dyn")
so the delegate function is now watching a removed .dyn
.
Move your delegation match to $("#main-content")
and you'll maintain an active "live" or "delegate" watcher that will correctly bind your defined click handler to new .dyn a
elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.