Javascript pushState重新加载页面
我试图遵循此处使用的示例: 我决定使用jQuery的.load()代替JSON 这是我的密码:Javascript pushState重新加载页面,javascript,jquery,html,Javascript,Jquery,Html,我试图遵循此处使用的示例: 我决定使用jQuery的.load()代替JSON 这是我的密码: $(function() { $('a').click(function(e) { $('img#logo').stop().hide().fadeIn( "slow" ); href = $(this).attr("href"); loadContent(href); // HI
$(function() {
$('a').click(function(e) {
$('img#logo').stop().hide().fadeIn( "slow" );
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$('#load').load( url + " #load2").stop().hide().fadeIn( 'slow' );
}
示例的loadContent函数:
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
HTML:
安迪·西蒙
西蒙
安迪·潘迪之家
当我点击一个链接时,页面会重新加载,这正是我试图阻止的。我以为我的e.preventDefault()会阻止这一切。感谢您的帮助 您可以将“return false;”在您的js代码中,防止其上载:
$('a').click(function(e) {
e.preventDefault();
$('img#logo').stop().hide().fadeIn( "slow" );
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
return false;
});
已尝试,但仍在重新加载页面。使用html Included编辑我的帖子可能会出现一些错误,
preventDefault
因此无法执行。尝试使用firebug控制台之类的东西,打开“请勿清洁”(或类似)选项。它将向您显示页面上JS中的错误
$('a').click(function(e) {
e.preventDefault();
$('img#logo').stop().hide().fadeIn( "slow" );
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
return false;
});