在 jQuery 中使用 window.location.hash
我想使用 jQuery 制作一个褪色导航菜单,其中与当前页面对应的“按下”按钮的行为与“未按下”按钮不同(具体来说,它在悬停时不会褪色为不同的颜色)。如果我查看 www.guitaracademy.nl 上的示例,我会发现他们使用带有 window.location.hash 属性的本机 JavaScript。
但是,我似乎无法将此哈希值放入 jQuery 中。这是一个示例脚本:
<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>
加载此页面后,我单击“首先单击我”链接;然后在地址栏中我看到原始 URL 后附加了“#test”。但是,如果我单击“然后单击我”div,我会看到一个空警报。看起来哈希值没有“更新”。
我将非常感谢对此的任何帮助。
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.
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>
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'.
I would greatly appreciate any help on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试将对哈希的调用移至函数内部,以便每次调用单击时都会调用它。按照您的方式,它仅在页面初始加载时加载。
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.
尝试将
var p=window.location.hash;
放入您的点击侦听器中:Try putting
var p=window.location.hash;
inside your click-listener:哈希正在更新,但在这种情况下变量“p”没有更新。
这里的赋值语句
仅在页面加载时执行一次。所以在加载时 P 的值是空的,而且永远都是空的。
而不是
尝试
或在点击回调中移动分配。即就在警报声明之上
The hash is getting upadated but in this case the variable 'p' is not getting updated.
Here the assignment statement
is executed only once when the page is loaded. So at the time of loading the value of P is empty, and always it will be empty.
Instead of
try
or move the assignment inside the click callback. i.e just above alert statement
您的
#clickme
div 函数永远不会尝试更新哈希值。如果您希望代码更新哈希值,则必须像这样操作它:Your function for the
#clickme
div never attempts to update the hash. If you were expecting your code to update the hash you'll have to manipulate it like: