追加/从当前URL不刷新,删除锚点名称 [英] append /remove anchor name from current url without refresh

查看:766
本文介绍了追加/从当前URL不刷新,删除锚点名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要上单击事件追加/删除锚点名称#on被添加到当前的URL无需重新加载页面,或使用的href ='#在'从链接,因为它使我的页面跳转

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

例如: http://www.mysite.com/page.html#on 这样我就可以得到在检测到来自该网址的用户
并调用在()功能

Eg: http://www.mysite.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;    
}); 

谢谢!

推荐答案

您并不真正需要的jQuery对于这一点,你可以获取/设置使用锚名称的location.hash 。如果你把它放在你的jQuery就绪功能,可以如果它被设置为某个特定值做一些动作:

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:

$(function(){
    // Remove the # from the hash, as different browsers may or may not include it
    var hash = location.hash.replace('#','');

    if(hash != ''){
        // Show the hash if it's set
        alert(hash);

        // Clear the hash in the URL
        location.hash = '';
    }
});

请注意,取消散时,尾随可能留在地址栏。如果你想以应对生活锚的变化,可以绑定一个回调到 hashchange 事件:

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 the hashchange event:

$(document).bind("hashchange", function(){
    // Anchor has changed.
});

如果您清除锚泊时要prevent你的页面跳转到顶部,可以将hashchange事件跳回previous滚动位置绑定。看看这个例子: http://jsfiddle.net/yVf7V/

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/

var lastPos = 0;

$('#on').click(function(){
    location.hash = 'blah';
});

$('#off').click(function(){
    lastPos = $(window).scrollTop();
    location.hash = '';
});

$(window).bind('hashchange',function(event){
    var hash = location.hash.replace('#','');
    if(hash == '') $(window).scrollTop(lastPos);
    alert(hash);
});

这篇关于追加/从当前URL不刷新,删除锚点名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆