我正在构建一个用户单击链接的基本站点,Jquery使用Jquery的load()通过异步请求填充id =“article”的div。 这是html:
<a href="#targetpage.html" onclick="menu('targetpage.html');">
TARGET PAGE</a>
这称之为非常简单的功能:
var menu = function(page){
$('#article').load(page);
//other code
};
工作正常。
但是,我希望用户能够使用永久链接,例如
www.mysite.com/index.html#targetpage.html
我希望js读取URL中的哈希值并相应地填充div。
问题在于,当我尝试将值window.location.hash传递给函数时,(在加载或就绪状态下),一切都被卡住了,我的js不再工作了。我也尝试使用ajax()而不是load()函数,但它也不接受该值。
修改 如果我试试
var thispage = document.location.hash;
var hash = thispage.replace( /^#/, '' );
并输入mysite.com/#page_one.html,警告说:
page_one.html,
哪个好!!!但是接下来
menu(hash);
不会将page_one.html的内容加载到div中。但是,单击我的菜单工作正常。 在js控制台中,我没有任何错误或警告。这是完整的代码:
<head><script type="text/javascript" charset="iso-8859-1">
var thispage = document.location.hash;
var hash = thispage.replace( /^#/, '' );
alert(hash);
menu = function(page){
$('#article').load(page);
};
menu(hash);
</script>
</head>
<body>
<div id="menu">
<ul>
<li><p class="menuvoice">
<a href="#page_one.html" onclick="menu('page_one.html');">
Page One</a></p></li>
<li><p class="menuvoice">
<a href="#page_two.html" onclick="menu('page_two.html');">
Page Two</a></p></li>
</ul>
</div>
<div id="article"></div>
答案 0 :(得分:1)
如何使用jQuery hashchange插件?
http://benalman.com/projects/jquery-hashchange-plugin/
它将处理在更改时解析当前哈希的工作(即,当您单击链接或使用新哈希重新加载页面时)。
编辑。示例用法:
$(function(){
// Bind an event to window.onhashchange that, when the hash changes, gets the
// hash and adds the class "selected" to any matching nav link.
$(window).hashchange( function(){
var hash = location.hash;
// Set the page title based on the hash.
document.title = 'The hash is ' + ( hash.replace( /^#/, '' ) || 'blank' ) + '.';
// Iterate over all nav links, setting the "selected" class as-appropriate.
$('#nav a').each(function(){
var that = $(this);
that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'selected' );
});
})
// Since the event is only triggered when the hash changes, we need to trigger
// the event now, to handle the hash the page may have loaded with.
$(window).hashchange();
});
答案 1 :(得分:1)
您的控制台中是否有任何错误输出?这有助于确定问题。
您可以尝试在将检索到的哈希值发送到“菜单”功能之前提醒它,这样您就会知道它是否正确(我想知道#符号是否没有附加到哈希值,这会对您的案例造成问题) ,我想)
答案 2 :(得分:1)
试试这个:
var hash = window.location.hash;
if (hash) {
var hash = hash.replace(/#/, '');
// Your function using hash
}