当点击链接时,维护标签值的干净方法是什么

What is a clean way of maintaining the hashtag value when links are clicked?

本文关键字:是什么 方法 标签 维护 链接      更新时间:2023-09-26

我的网站上没有外部链接,所以我想选择所有的锚标签:$('a'),并将当前的标签值附加到所有这些标签的href中,但这似乎是一个混乱的过程。有更好的方法吗?我的网站的url看起来是这样的:www.rsadler.com/html/home.html#chairsAndTables但当你点击我的任何链接时,url显然会更新,没有标签。谢谢

OP实际上意味着页面会发生变化,但哈希需要结转到后续的每个页面。

$('a').each(function(){
    var href=this.href.split('#')[0];
    $(this).attr('href', href + window.location.hash);
});

方法1:jQuery

$(document).ready(function() {
    $("a").each(function(){ this.src += window.location.hash; });
});

方法2:会话Cookie

window.onload = function() { 
    var winHash = window.location.hash;
    var cookieHash = unescape((document.cookie.match(new RegExp(''bhash=(.*?)(?:;|$)','i')) || [null,''])[1]);
    if(winHash == "" && cookieHash.length > 0)
        window.location.hash = cookieHash;
    else if(winHash != "")
        document.cookie = "hash=" + escape(winHash) + "; path=/";
}

注意我没有测试上面的JavaScript,所以可能存在语法错误。

在链接的点击事件处理程序中对事件调用preventDefault将阻止浏览器更新当前URL。