[英]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.