gpt4 book ai didi

javascript - 当哈希 anchor 位于 URL 中时显示选择的 DIV

转载 作者:行者123 更新时间:2023-12-01 01:12:38 25 4
gpt4 key购买 nike

我想在仅显示特定 anchor 链接 (myurl.com/#about) 时有条件地显示 div。我的 css 中的 .dynamic-content 设置为 display: none 。 #default-content 显示,所以我知道我已经接近了,但我对这个级别的脚本编写很陌生。让它发挥作用的最佳方法是什么?谢谢!

(function($) {
// Parse the URL parameter
function getParameterByName(name, url) {
if (!url) {
url = location.href.split("#").slice(-1)[0];
}

return url;

}
// Give the parameter a variable name
var dynamicContent = getParameterByName('#');

$(document).ready(function() {

// Check if the URL parameter is about
if (dynamicContent == 'about') {
$('#about').show();
}
// Check if the URL parameter is expertise
else if (dynamicContent == 'expertise') {
$('#expertise').show();
}
// Check if the URL parameter is contact
else if (dynamicContent == 'contact') {
$('#contact').show();
}
// Check if the URL parmeter is empty or not defined, display default content
else {
$('#default-content').show();
}
});
})(jQuery);
  <div id="default-content" class="dynamic-content">
This is the default content
</div>
<!-- Dynamic Section 1 -->
<div id="contact" class="dynamic-content">
Contact content
</div>
<!-- Dynamic Section 2 -->
<div id="expertise" class="dynamic-content">
Expertise content
</div>
<!-- Dynamic Section 3 -->
<div id="about" class="dynamic-content">
About content
</div>

最佳答案

你可以减少你的逻辑。您可以将有效哈希值映射到选择器,以供各部分显示它们。向上查找选择器,如果没有找到则默认,并显示该部分。

$(document).ready(function() {
var contentByHash = {
about: '#about'
, expertise: '#expertise'
, contact: '#contact'
};
var hash = window.location.hash.slice(1);

$(contentByHash[hash] || '#default-content').show();
});

关于javascript - 当哈希 anchor 位于 URL 中时显示选择的 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55033328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com