简体   繁体   中英

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:

<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.

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.

Once you change the page on websites ( not single page apps ) , javascript ' forgets ' what you have done before.

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.

You can use location.hash to get the # anchor from your url.

In the below example i changed the location.hash value to show you that the solution works. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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