【问题标题】:append /remove anchor name from current url without refresh从当前 url 追加/删除锚名称而不刷新
【发布时间】:2011-08-21 04:03:46
【问题描述】:

我希望在单击事件时附加/删除要添加到当前 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;    
}); 

【问题讨论】:

    标签: jquery url append anchor


    【解决方案1】:

    您实际上并不需要 jQuery,您可以使用 location.hash 获取/设置锚点名称。如果你把它放在你的 jQuery 就绪函数中,如果它被设置为某个值,你可以做一些动作:

    $(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事件:

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

    如果想在清除锚点的时候防止页面跳转到顶部,可以绑定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);
    });
    

    【讨论】:

    • 谢谢老兄,它现在工作正常,除了我想将 location.hash 设置为空的部分,正如你所说,它将 # 保留在 url 的末尾,它使我的页面跳转至顶...有点烦人,但我希望找到解决方法。再次感谢;)
    • 我添加了跳跃问题的解决方案。
    【解决方案2】:

    如果您使用的是 jquery,请尝试此代码

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

    【讨论】:

    【解决方案3】:

    调用history.pushState({}, "", link) 与设置window.location = "#foo" 类似,两者都将创建并激活另一个与当前文档关联的历史条目。

    请注意pushState() 永远不会触发 hashchange 事件,即使新 URL 与旧 URL 的不同之处仅在于其哈希值。

    const url = new URL(window.location);
    url.hash = '#foo';
    window.history.pushState({}, '', 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

    【讨论】:

      猜你喜欢
      • 2019-06-02
      • 2013-06-10
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 2020-06-25
      相关资源
      最近更新 更多