我有一些jQuery/JavaScript代码,我想只在URL中有一个散列(#)锚链接时运行。如何使用JavaScript检查这个字符?我需要一个简单的全方位测试,可以检测到如下url:
example.com/page.html #锚 example.com/page.html # anotheranchor
基本上是这样的:
if (thereIsAHashInTheUrl) {
do this;
} else {
do this;
}
我有一些jQuery/JavaScript代码,我想只在URL中有一个散列(#)锚链接时运行。如何使用JavaScript检查这个字符?我需要一个简单的全方位测试,可以检测到如下url:
example.com/page.html #锚 example.com/page.html # anotheranchor
基本上是这样的:
if (thereIsAHashInTheUrl) {
do this;
} else {
do this;
}
当前回答
我注意到所有这些答案都主要检查window.location.hash,这使得编写测试变得困难。
const hasHash = string => string.includes('#')
你也可以像这样从url中删除散列:
const removeHash = string => {
const [url] = string.split('#')
return url
}
最后你可以把逻辑组合在一起:
if(hasHash(url)) {
url = removeHash(url)
}
其他回答
有时您会得到完整的查询字符串,例如“#anchorlink?”firstname =马克”
这是我获取哈希值的脚本:
var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);
returns -> #anchorlink
位置哈希的简单使用:
if(window.location.hash) {
// Fragment exists
} else {
// Fragment doesn't exist
}
大多数人都知道document.location中的URL属性。如果您只对当前页面感兴趣,那就太好了。但问题在于能否解析页面上的锚,而不是页面本身。
大多数人似乎忽略了这些URL属性也可以用于锚定元素:
// To process anchors on click
jQuery('a').click(function () {
if (this.hash) {
// Clicked anchor has a hash
} else {
// Clicked anchor does not have a hash
}
});
// To process anchors without waiting for an event
jQuery('a').each(function () {
if (this.hash) {
// Current anchor has a hash
} else {
// Current anchor does not have a hash
}
});
下面是一个简单的函数,返回true或false(有/没有标签):
var urlToCheck = 'http://www.domain.com/#hashtag';
function hasHashtag(url) {
return (url.indexOf("#") != -1) ? true : false;
}
// Condition
if(hasHashtag(urlToCheck)) {
// Do something if has
}
else {
// Do something if doesn't
}
在这种情况下返回true。
基于@jon-skeet的评论。
我注意到所有这些答案都主要检查window.location.hash,这使得编写测试变得困难。
const hasHash = string => string.includes('#')
你也可以像这样从url中删除散列:
const removeHash = string => {
const [url] = string.split('#')
return url
}
最后你可以把逻辑组合在一起:
if(hasHash(url)) {
url = removeHash(url)
}