[英]Showing content based on a URL Anchors
I have links that lead to another page with different contents.我有指向另一个内容不同的页面的链接。
<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>
This the code on the /services
page:这是
/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>
I found the bellow JS, but it works only when clicking on the anchor link on the same page.我找到了 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();
});
I need is to display only the content related to the anchor link when load the /services
page.我需要的是在加载
/services
页面时仅显示与锚链接相关的内容。
Once you change the page on websites ( not single page apps ) , javascript ' forgets ' what you have done before.一旦您更改了网站上的页面(而不是单页应用程序),javascript 就会“忘记”您之前所做的事情。
So for your logic to work it can't be inside a click event which happened on another page.因此,为了让您的逻辑正常工作,它不能在发生在另一个页面上的点击事件中。 It should be inside a document.ready or window.onload function.
它应该在 document.ready 或 window.onload 函数内。
You can use location.hash
to get the #
anchor from your url.您可以使用
location.hash
从您的 url 中获取#
锚点。
In the below example i changed the location.hash
value to show you that the solution works.在下面的示例中,我更改了
location.hash
值以向您展示该解决方案有效。 You can skip that first line and just use the next ones.您可以跳过第一行,直接使用下一行。
$(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.