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

问题描述

我希望在点击事件时附加/删除锚名称#on"以添加到当前 url 而不重新加载页面,或者使用链接中的 href='#on' 因为它使我的页面跳转

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.example.com/page.html#on 这样我就可以检测到来自该 url 的用户并调用 On() 函数

Eg: http://www.example.com/page.html#on so I can get the detect the users that come from that urland 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.
});

如果你想防止你的页面在清除锚点时跳到顶部,可以绑定hashchange事件跳回到之前的滚动位置.看看这个例子: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 附加/删除锚点名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 18:56