如何将字符串添加到window.location.hash

发布于 2025-01-16 21:25:11 字数 364 浏览 2 评论 0原文

任何想法如何写这个:

var hashValue = "#" + window.location.hash.substr(1);
$([document.documentElement, document.body]).animate({
        scrollTop: $(hashValue).offset().top
        
}, 500);

没有收到此错误:

未捕获错误:语法错误,无法识别的表达式:#

它的工作原理是这样的,但我不想在控制台中看到此错误。

Any ideas how can I write this:

var hashValue = "#" + window.location.hash.substr(1);
$([document.documentElement, document.body]).animate({
        scrollTop: $(hashValue).offset().top
        
}, 500);

Without getting this error:

Uncaught Error: Syntax error, unrecognized expression: #

It is working like that, but I don't want to see this error in the console.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

零崎曲识 2025-01-23 21:25:11
var hashValue = "#" + window.location.hash.substring(1);

$([ document.documentElement, document.body ]).animate({
  scrollTop: hashValue === '#' ? 0 : $(hashValue).offset().top
}, 500);

我们假设 window.location.hash 是空字符串。在本例中,hashValue"#"

因此 jQuery 调用 $(hashValue) 无法将其识别为元素 ID,因此会引发语法错误。

var hashValue = "#" + window.location.hash.substring(1);

$([ document.documentElement, document.body ]).animate({
  scrollTop: hashValue === '#' ? 0 : $(hashValue).offset().top
}, 500);

Let’s just assume window.location.hash is the empty string. In this case hashValue is "#".

So the jQuery call $(hashValue) doesn’t recognize it as an element ID, so it throws a syntax error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文