在jQuery中使用window.location.hash [英] Using window.location.hash in jQuery
问题描述
我想用jQuery制作一个颜色渐变导航菜单,其中与当前页面对应的按下按钮的行为与未按下按钮的行为不同(具体来说,悬停时它不会褪色成不同的颜色)。如果我看一下www.guitaracademy.nl中的示例,我会发现它们使用原生javascript和window.location.hash属性。
I would like to make a color fading navigation menu using jQuery, in which the "pressed" button corresponding to the current page behaves differently from the "unpressed" button (specifically, it doesn't fade to a different color upon hovering). If I look at the example at www.guitaracademy.nl, I see that they use native javascript with the window.location.hash property.
然而,我不能似乎将这个哈希值放入jQuery中。以下是一个脚本示例:
However, I can't seem to get this hash into jQuery. Here is an example script:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var p=window.location.hash;
$("#clickme").click(function(){
alert(p)
});
});
</script>
</head>
<body>
<a href="#test">Click me first</a>
<div id="clickme">Then click me</div>
</body>
</html>
加载此页面后,我点击Click me first链接;然后在地址栏中,我看到#test附加到原始URL。但是,如果我然后点击然后点击我div我看到一个空的警报。看起来哈希并不是'更新'。
After loading this page, I click the "Click me first" link; then in the address bar I see "#test" appended to the original URL. However, if I then click the "Then click me" div I see an empty alert. It seems like the hash is not 'updating'.
我非常感谢任何帮助。
推荐答案
尝试将哈希的调用移动到函数内部,以便每次调用click时都会调用它。
Try moving the call for the hash to inside the function so that it gets called each time the click is called. The way you had it, it was only loading on the initial load of the page.
$(function(){
$("#clickme").click(function(){
var p=window.location.hash;
alert(p)
});
});
这篇关于在jQuery中使用window.location.hash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!