繁体   English   中英

基于 URL 锚点显示内容

[英]Showing content based on a URL Anchors

我有指向另一个内容不同的页面的链接。

<ul class="menu">
   <li><a href="/services#item1" class="menu-btn">Item 1</a></li>
   <li><a href="/services#item2" class="menu-btn">Item 2</a></li>
   <li><a href="/services#item3" class="menu-btn">Item 3</a></li>
</ul>

这是/services页面上的代码:

<div class="menu-content item-1">Content item 1</div>
<div class="menu-content item-2">Content item 2</div>
<div class="menu-content item-3">Content item 3</div>

我找到了 bellow JS,但它仅在单击同一页面上的锚链接时才有效。

var $content = $('.menu-content');

function showContent(type) {
$content.hide().filter('.' + type).show();
}

$('.menu').on('click', '.menu-btn', function(e) {
   showContent(e.currentTarget.hash.slice(1));
   e.preventDefault();
}); 

我需要的是在加载/services页面时仅显示与锚链接相关的内容。

一旦您更改了网站上的页面(而不是单页应用程序),javascript 就会“忘记”您之前所做的事情。

因此,为了让您的逻辑正常工作,它不能在发生在另一个页面上的点击事件中。 它应该在 document.ready 或 window.onload 函数内。

您可以使用location.hash从您的 url 中获取#锚点。

在下面的示例中,我更改了location.hash值以向您展示该解决方案有效。 您可以跳过第一行,直接使用下一行。

 $(document).ready(function() { location.hash = "item1"; // skip this const myHash = location.hash.substr(1) $('.menu-content').hide().filter(`.${myHash}`).show(); // or use : $('.menu-content').not(`.${myHash}`).hide() })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="menu-content item1">Item 1</div> <div class="menu-content item2">Item 2</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM