如何从URL链接一个散列链接到Javascript内容

How to link a hash link from the URL to Javascript content?

本文关键字:链接 一个 内容 Javascript URL      更新时间:2023-09-26

我曾经使用jQuery UI为我的一个项目添加选项卡功能。

一切都工作得很好,我注意到每个选项卡都绑定到一个URL哈希标签(我不知道你用英语说)。例如,一旦我点击了第一个选项卡,#Tab0就被添加到我的URL中。

我想在我当前的项目中重现此行为。但是我没有使用jQuery UI选项卡,我正在移植一个桌面应用程序,并且有JavaScript按钮可以在我的页面内编写和替换内容(以不同页面的方式,但不需要重新加载)。

我如何继续模仿这个行为?我是否必须手动获取URL中的标签,并通过JavaScript做相应的事情?

谢谢,

你可以这样做:

用当前url的哈希值创建一个url:

var url = window.location.href + '#Tab0';

从当前url读取散列:

var hash;
if (window.location.href.indexOf('#') > -1)
{
    hash = url.split('#')[1];
}

您可以使用location.hash:

//you can set hash
location.hash = "something"; 
//and read it eg. http://domain.com#something
console.log(location.hash); //will return the current hash value 'something'

另外,你必须记住,如果你的锚标签有散列href属性,例如<a href="#something">,它将自动追加到当前url和浏览器将尝试在页面上找到给定的id。当然,你可以阻止这种默认行为。