gpt4 book ai didi

javascript - PushState 重新加载页面

转载 作者:行者123 更新时间:2023-11-28 09:03:48 25 4
gpt4 key购买 nike

我试图遵循此处使用的示例:http://html5.gingerhost.com/我决定使用 jQuery 的 .load() 代替 JSON,

这是我的代码:

    $(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:

<head> 
<meta charset="utf-8">
<title>Andy Simon</title>

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="javascript.js"></script>

<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Raleway:100' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="main">
<div id="top">
<div id="logo">
<div>
<a id="logo" href="index.html"><img id="logo" src="logo1.png" /></a><span id="logo_text">simon</span>
</div>
</div>
<div id="nav">
<a class="nav_link" id="work" href="work.html"> work . </a>
<a class="nav_link" id="work" href="work.html"> about . </a>
<a class="nav_link" id="work" href="contact.html"> contact </a>
</div>
</div>

<div id ="middle">

<div id="load">
<div id="load2">
home home andy pandy home home home
</div>
</div>

</div>

<div id="foot">
</div>

</div>
</body>

当我点击链接时,页面会重新加载,这是我试图阻止的。我以为我的 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;
});

关于javascript - PushState 重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17375373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com