在没有刷新的情况下追加/删除当前网址的锚名称

Adr*_*ian 34 url anchor jquery append

我希望在click事件上附加/删除锚名称"#on"以添加到当前url而不重新加载页面,或者使用链接中的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;    
}); 
Run Code Online (Sandbox Code Playgroud)

Dar*_*JDG 61

你真的不需要jQuery,你可以使用获取/设置锚名称location.hash.如果你把它放在你的jQuery ready函数中,你可以做一些动作,如果它被设置为某个值:

$(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 = '';
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,删除哈希时,尾随#可能会保留在地址栏中.如果要响应锚点的实时更改,可以将回调绑定到hashchange事件:

$(document).bind("hashchange", function(){
    // Anchor has changed.
});
Run Code Online (Sandbox Code Playgroud)

如果要在清除锚点时阻止页面跳到顶部,可以绑定hashchange事件以跳回到上一个滚动位置.看看这个例子: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);
});
Run Code Online (Sandbox Code Playgroud)

  • 我为跳跃问题添加了一个解决方案. (3认同)

Ale*_*mas 17

如果您正在使用jquery尝试此代码

$("a[href^=#]").on("click", function(e) {
    e.preventDefault();
    history.pushState({}, "", this.href);
});
Run Code Online (Sandbox Code Playgroud)