如何显示隐藏的 link 中的特定部分

How to show a specific section from a link that is hidden

我有多个 link 转到同一页面,但我希望显示该页面的不同部分(最好在页面顶部)。问题是,这些部分在页面加载时隐藏,它们所在的容器也是如此。我解决了如何让容器显示,但是当我只想要我点击的部分时,它显示了所有不同的部分,从link,显示。即:

我有这些 link:

<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 的 link,我希望显示 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();
    }
}*/

您可以尝试使用 CSS 来控制可见性,只需使用您的 JS 切换 class。

JS:

$('#service-display-box').addClass('visible');// Make the wrapper visible
$('#service-item-box').removeClass('visible');// Double-check all the other boxes are still hidden
$('#service' + sectionName).addClass('visible');// Make the target box visible

CSS:

#service-display-box,
#service-item-box{
    display:none;
}
#service-item-box.visible,
#service-item-box.visible{
    display:block;
}

看来您的部分选择器格式不正确。本质上是这样的:

  1. 您点击<a href="serviceCheck1#service1">Service 1</a>
  2. serviceCheck1 页面加载。
  3. 这一行 运行s: var sectionName = window.location.hash.slice(1);
  4. sectionName 现在包含 "service1"
  5. 这一行 运行s: $('#service' + sectionName).show().siblings().hide();
  6. 计算结果为 $('#serviceservice1').show().siblings().hide();
  7. 浏览器找不到 ID 为 serviceservice1
  8. 的元素
  9. 没有任何反应:)

相反,由于 window.location.hash 已经包含 #service1,因此 运行 如下:

$(window.location.hash).show().siblings().hide();

这将找到合适的元素,显示它,并隐藏它的兄弟姐妹。