Javascript 根据url中的#锚点执行/触发脚本?
我有一个中心页面Javascript 根据url中的#锚点执行/触发脚本?,javascript,jquery,html,anchor,Javascript,Jquery,Html,Anchor,我有一个中心页面example.com/info/requirements,其中包含运行不同应用程序的要求。默认情况下,仅显示显示旗舰应用程序需求的div,用户可以单击按钮打开/关闭其他div <a id="main-app"></a> <div id="req-container-main" class="invisible"> [Requirements are listed here] </div> <a id="app2"&g
example.com/info/requirements
,其中包含运行不同应用程序的要求。默认情况下,仅显示显示旗舰应用程序需求的div,用户可以单击按钮打开/关闭其他div
<a id="main-app"></a>
<div id="req-container-main" class="invisible">
[Requirements are listed here]
</div>
<a id="app2"></a>
<div id="req-container-app2" class="invisible">
[Requirements are listed here]
</div>
<a id="app2"></a>
<div id="req-container-app3" class="invisible">
[Requirements are listed here]
</div>
<a id="app4"></a>
<div id="req-container-app4" class="invisible">
[Requirements are listed here]
</div>
[此处列出了要求]
[此处列出了要求]
[此处列出了要求]
[此处列出了要求]
我有每个应用程序的登录页。它们包含一个指向需求页面的链接,其中包含一个锚,如example.com/info/requirements\app3
现在我正在寻找一种方法——使用JS/jQuery——在访问页面时检查是否存在“锚定”,然后触发我的openReqDiv('#app3')代码>我已经准备好的功能
有人能告诉我什么时候,在哪里,如何检查锚并触发我的脚本吗?谢谢大家! 您可以通过以下jQuery解决方案检查DOM元素的存在性:
if($('#anchor').length > 0) {
openReqDiv('#app3');
}
您可以使用document.location.href方法通过Javascript实现这一点
例如:
// When the page loads...
$( document ).ready(function() {
// Check if the hash is in the URL
if ( document.location.href.indexOf('requirements#app3') > -1 ) {
// Init your function
openReqDiv('#app3');
}
});
您可以修改此函数并将其绑定到window.load事件。因此,一旦用户登陆页面,您的函数就会执行
祝你好运 这件事叫做路由。你的方法很简单,但不用担心。只要做:
var hash = window.location.hash;
switch(hash){
case '#app2':
$("#app2").removeClass('invisible');
break;
}
但是,最终您会希望检测对哈希的更改。只需使用一个插件,如。另一种选择是使用某种框架(角度、余烬…谢谢,使用window.location.hash似乎是最干净的解决方案。无需监控哈希值的更改,该脚本只需在每次加载页面时运行一次。我封装了您签入$(document).ready(function(){})代码>并且它按预期工作。哦,太好了。祝你的项目好运。谢谢你的回答。我将您的文档.ready
与@Martin Gottweis hash(而不是href)组合在一起,效果很好