从当前 url 添加/删除锚点名称而不刷新
我希望在单击事件上附加/删除要添加到当前网址的锚点名称“#on”,而无需重新加载页面,或者使用链接中的 href='#on',因为它会使我的页面跳转
例如: http://www.example.com/page.html#on 这样我就可以检测到来自该 url 的用户 并调用On()函数
function On()
{
//append to current url the anchor "#on"
}
function Off()
{
//remove from the current url the anchor "#on"
}
$('.on').live('click', function() {
On();
return false;
});
$('.off').live('click', function() {
Off();
return false;
});
I want that on click event to append/remove the anchor name "#on" to be added to the current url without reloading the page, or use the href='#on' from links because it makes my page jump
Eg: http://www.example.com/page.html#on so I can get the detect the users that come from that url
and call the On() function
function On()
{
//append to current url the anchor "#on"
}
function Off()
{
//remove from the current url the anchor "#on"
}
$('.on').live('click', function() {
On();
return false;
});
$('.off').live('click', function() {
Off();
return false;
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您实际上并不需要 jQuery,您可以使用
location.hash
获取/设置锚点名称。如果将其放入 jQuery 就绪函数中,并且将其设置为特定值,则可以执行某些操作:请注意,删除哈希时,尾随的
#
可能会保留在地址栏中。如果你想响应锚点的实时变化,你可以绑定一个回调到hashchange
事件:如果你想防止你的页面在清除锚点时跳到顶部,你可以绑定hashchange跳回到上一个滚动位置的事件。查看此示例:http://jsfiddle.net/yVf7V/
You don't really need jQuery for that, you can get/set the anchor name using
location.hash
. If you put it in your jQuery ready function, you can do some action if it's set to a certain value:Note that when removing the hash, the trailing
#
might stay in the address bar. If you want to respond to live changes of the anchor, you can bind a callback to thehashchange
event:If you want to prevent your page jumping to the top when clearing the anchor, you can bind the hashchange event to jump back to the previous scroll position. Check out this example: http://jsfiddle.net/yVf7V/
如果你使用 jquery 试试这个代码
if you are using jquery try this code
调用
history.pushState({}, "", link)
与设置window.location = "#foo"
类似,两者都会创建并激活另一个历史记录与当前文档关联的条目。请注意,
pushState()
永远不会导致触发 hashchange 事件,即使新 URL 与旧 URL 仅在哈希值上有所不同。https://developer.mozilla.org/en- US/docs/Web/API/History/pushState#examples
https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event
Calling
history.pushState({}, "", link)
is similar to settingwindow.location = "#foo"
, in that both will also create and activate another history entry associated with the current document.Note that
pushState()
never causes a hashchange event to be fired, even if the new URL differs from the old URL only in its hash.https://developer.mozilla.org/en-US/docs/Web/API/History/pushState#examples
https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event