Answer 1在前进和后退时获得标题工作
就我所知,你想要从链接中更改文档标题 html,从一个div加载。 当你通过 jQuery .load 加载一个文件时,你只是在它的一个ajax请求之后插入完整的响应文本。 所以所有不应该在div中的东西,如 title 或者 meta 标签。 但是,当前文档的标题( http://bramvanroy.be/sectionLoaderTest/index.html 在 title 中定义,它是 inside 标记而不是标记 inside,所以这就是文档标题不改变的原因。
那我怎么修复它?
很好的问题是 title 元素 inside的div 元素无效,大多数浏览器将删除它,这样你就不能只使用它:document.title = $("#sectionContainer title").text();
因为 title 元素可能不存在。
我们所需要的是 jQuery .load 函数的直接响应。 我可以通过向函数中添加回调参数来获取它:$("#sectionContainer")
. hide()
. load(newLoadedHtml, function(responseText) {
document.title = $(responseText).filter("title").text();
})
. fadeIn("fast");
你可能不明白我为什么使用 .filter 而不是 .find 函数。 这是因为jQuery是在解析 html 。head 和 body 标签,而不是删除子元素。
应答 2 - 优化 mainpage的加载时间
文档正从顶部加载到底部。
所以首先,应该加载 JavaScript 等等,然后加载主文档。 因为jQuery在执行之前总是等待文档,所以将所有 script 元素放在 body 之前都不是很好的想法。
顺便说一下,我第一次只有这个问题,所有的东西都被缓存,文档加载非常快。
在向前和向后 active active
我将在 a 元素的href 属性中表示循环,并将它与 History.getState() 中的数据进行比较。 应该很简单。
你在代码中犯了一些错误,你的代码是固定的:
你将哈希 #content 附加到所有 url 。 它没有意义,它将被jQuery再次删除: https://github.com/jquery/jquery/blob/master/src/ajax.js#L617 ( 来自行: 158.190.337.- rhash处于在线 6状态$(document).ready(function () {
var firstLink = $("ul> li:first-child> a");
var menuLink = $("ul> li> a");
var firstLoadedHtml = firstLink.attr("href");
$("#sectionContainer").hide().load(firstLoadedHtml).fadeIn("fast");
firstLink.addClass("active");
menuLink.click(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var newLoadedHtml = $(this).attr("href");
History.pushState(null, newLoadedHtml, newLoadedHtml);
$("#sectionContainer")
. hide()
. load(newLoadedHtml, function(responseText) {
document.title = $(responseText).filter("title").text();
})
. fadeIn("fast");
});
History.Adapter.bind(window,"statechange", function() {
menuLink.removeClass("active");
$("a[href='" + History.getState().title +"']").addClass("active");
$('#sectionContainer').load(document.location.href, function(responseText) {
document.title = $(responseText).filter("title").text();
});
});
});