【发布时间】:2020-06-14 05:03:51
【问题描述】:
我正在使用我编写的 jQuery 脚本在我的网站上加载内容而不刷新页面,并且除了后退/前进按钮之外一切正常。我正在使用哈希链接并基于此加载我的 php 文件。
....
<li><a id="theShopLink" class="theMainLinks" href="#shopFrame">SHOP</a>
....
$('.theMainLinks').click(function() {
var dest = $(this).prop("hash").substring(1);
$('.theMainLinks').removeClass('active');
$(this).addClass('active');
if ($('#fullFrame > div').is(':visible')) {
$('#homeFrame').addClass('animated fadeOutLeft');
$('#homeFrame').html('');
}
console.log(dest);
$("<style>html { background: #000; }</style>").appendTo("head");
$('#nextFrame').html('<div id="loading"><img id="loading-image" src="/wp-content/uploads/assets/loader.gif" alt="Loading..." /></div>').load('/frames/' + dest + '.php');
});
我尝试搜索并找到了一些使用 html5 window.history.pushState(); 的示例,但我不确定如何使用我当前的代码来处理它而无需重写脚本。此外,网址中的# 看起来很难看,无论如何?
我不打算使用除 jQuery 之外的任何类型的插件/依赖项,如果可能的话,我不打算使用最干净/最简单的代码。请解释一下,以便我理解,因为我需要对框架内的子导航链接做类似的事情,并将重用该功能。
更新
在初始网站加载或刷新时,我使用以下函数来确定要加载的内容。 -
$(function() {
if (window.location.hash) {
var target = window.location.hash.substring(1);
var hash = window.location.hash;
if (hash.toLowerCase().indexOf("frame") >= 0) {
$('#homeFrame').html('');
$('#homeFrame').html('<div id="loading"><img id="loading-image" src="/wp-content/uploads/assets/loader.gif" alt="Loading..." /></div>').load('/frames/' + target + '.php');
} else if (hash.toLowerCase().indexOf("shop-") >= 0) {
$('#homeFrame').html('');
$('#homeFrame').html('<div id="loading"><img id="loading-image" src="/wp-content/uploads/assets/loader.gif" alt="Loading..." /></div>').load('/frames/shopFrame.php');
} else if (hash.toLowerCase().indexOf("news-") >= 0) {
......etc......
} else if (hash.toLowerCase().indexOf("/") >= 0) {
var newTar = target.split('/');
$('#homeFrame').html('');
$('#homeFrame').html('<div id="loading"><img id="loading-image" src="/wp-content/uploads/assets/loader.gif" alt="Loading..." /></div>').load('/general/' + newTar + ' #patchnotesMain');
} else {
// Fragment doesn't exist
$('#homeFrame').html('<div id="loading"><img id="loading-image" src="/wp-content/uploads/assets/loader.gif" alt="Loading..." /></div>').load('/' + target + ' #newContent');
}
} else {
$('#homeFrame').html('<div id="loading"><img id="loading-image" src="/wp-content/uploads/assets/loader.gif" alt="Loading..." /></div>').load('/frames/homeFrame.php');
}
});
【问题讨论】:
-
请同时提供 .load() 回调
-
@EriksKlotins 我不确定你的意思。使用上面提到的加载函数将我的内容加载到 div 中。除了网站加载/重新加载之外,我没有其他任何东西我检查哈希以查看要加载的页面。如果有帮助,我会添加该部分。
标签: javascript html jquery ajax html5-history