我在我的网站上设置了一个hashchange功能,允许我在'about'页面上的6个不同部分之间切换,这很好用,它将哈希附加到每个部分没有问题。
我遇到的问题是当你从另一个页面链接到这些哈希时,他们无法加载相关内容,例如:www.thisisawebsite.com/about/#section03
当您在about页面上时,哈希工作正常,但是来自其他任何地方它只会加载section01。
jQuery(document).ready(function(){
jQuery('.about').hide();
jQuery('#section01').show();
jQuery(function(){
jQuery(window).on('hashchange', function(){
var hash = window.location.hash;
jQuery('.sub-menu').each(function(){
jQuery('.about').hide();
if (jQuery(this).attr('hook') === hash.replace('#section', '')) {
jQuery('#section'+jQuery(this).attr('hook')).fadeIn();
return false;
}
});
});
});
jQuery(window).trigger('hashchange');
});
这可以修复,因为我想要使用hashchange函数的整个想法是这样我没有必须有6个单独的页面,我可以在一个页面上显示/隐藏每个部分并使用哈希链接到它们
答案 0 :(得分:1)
如果您已经加载了已经存在哈希标记的页面,那么窗口上的hashchange事件是否会触发?如果它没有你的问题,我建议将每个循环重构为一个单独的函数,然后在文档就绪,只需调用它来查看是否存在任何哈希标记,然后淡入内容。
这样的事情(我没有尝试过这个,因为我没有你的DOM,但你会明白这一点。
jQuery(document).ready(function(){
jQuery(window).on('hashchange', function(){
var hashFound = determineContent();
if(hashFound) return false;
});
function determineContent(){
var hash = window.location.hash;
jQuery('.about').hide();
jQuery('.sub-menu').each(function(){
if (jQuery(this).attr('hook') === hash.replace('#section', '')) {
jQuery('#section'+jQuery(this).attr('hook')).fadeIn();
return true;
}
});
// no hash found, so let's show #section01
jQuery('#section01').show();
return false;
}
determineContent();
});
如果这不起作用,那么jQuery就有一个很棒的插件,它也可以处理ajax事件。我一直在使用这个基于js的web应用程序。