【发布时间】:2016-09-09 20:08:43
【问题描述】:
我有多个指向同一页面的链接,但我希望显示该页面的不同部分(最好在页面顶部)。问题是,这些部分在页面加载时隐藏,它们所在的容器也是如此。我解决了如何让容器显示,但是当我只想要我点击的那个时,它会显示所有不同的部分,从链接,显示。即:
我有这些链接:
<a href="serviceCheck1#service1">Service 1</a>
<a href="serviceCheck1#service2">Service 2</a>
<a href="serviceCheck1#service3">Service 3</a>
然后在serviceCheck1 页面上我有这个 HTML:
<div id="service-display-box">
<div id="service-display-box-container">
<div class="service-item-box" id="service1">
<div class="service-item-title">Service 1</div>
</div>
<div class="service-item-box" id="service2">
<div class="service-item-title">Service 2</div>
</div>
<div class="service-item-box" id="service3">
<div class="service-item-title">Service 3</div>
</div>
<div class="service-item-box" id="service4">
<div class="service-item-title">Service 4</div>
</div>
<div class="service-item-box" id="service5">
<div class="service-item-title">Service 5</div>
</div>
<div class="service-item-box" id="service6">
<div class="service-item-title">Service 6</div>
</div>
</div>
</div>
如果我单击显示服务 2 的链接,我希望显示 service-display-box,然后显示 #service2 div,然后不显示其所有兄弟。
这是我的 javascript:
$(function(){
//get the section name from hash
var sectionName = window.location.hash.slice(1);
//then show the section
$('#service-display-box').show();
//$('#' + sectionName ).show();
$('#service' + sectionName).show().siblings().hide();
})
/*var index = location.hash.indexOf('#service');
if(index > -1) {
var serviceId = parseInt(location.hash.substring(index));
if(serviceId) {
$('#service-display-box').show();
$('#service' + serviceId).show().siblings().hide();
}
}*/
【问题讨论】:
-
您的
sectionName变量将在第一行代码之后包含"section1"。所以最后一行会显示为$('#sectionsection1')...,这似乎不是你想要的。 -
@MikeMcCaughan 你是说要更改我的链接以仅显示
#1还是从$('#service' + sectionName).show().siblings().hide();中取出#service? -
我尝试这样做,但没有得到任何不同的结果。我试过
$(sectionName).show().siblings().hide(); -
只要使用
$(window.location.hash)... -
@MikeMcCaughan 谢谢,做到了!留下一个答案,我会投票给你。
标签: javascript jquery hyperlink anchor show