如何在 JavaScript 中判断 url 有一个 # 查询字符串

我想在 JS 中编写一个脚本来判断 URL 是否具有 #st 这样https://hoogabooga/t/wow.html#btn1 我可以让它可以更改该元素的背景颜色。

因为我正在使页面不可滚动且很小我需要制作扩展每种类型内容的一部分的页面......(如果应该有更多)并制作按钮以转到新页面上的内容那就是完成剩下的事情,我知道如何做到这一点的方法是将它们发送到带有wow.html#btn1页面无法滚动的页面。


凤凰求蛊
浏览 119回答 2
2回答

慕田峪7331174

如果你想检测哈希值的变化:function hashHandler() {  console.log('The hash has changed to ' + location.hash);}window.addEventListener('hashchange', hashHandler, false);如果您只想查看当前哈希是什么:console.log(location.hash)

沧海一幻觉

您可以从中获取哈希值window.location.hash。例如 .com/#btn1,window.location.hash将包含btn1.听起来您正在尝试响应散列更改,例如将散列放在锚点的 href 属性中。为此,你想要window.onhashchange.window.onhashchange = function(){&nbsp; &nbsp; var newHash = window.location.hash;&nbsp; &nbsp; if(newHash == "something")&nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //load new page&nbsp;&nbsp; &nbsp; }}郑重声明,这可以通过点击事件轻松实现。<a href="#" onclick="doSomething()">
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript