简体   繁体   中英

When I click the anchor tag, page re-direct to to another page. Then I need to load specific content using Java Script

In index.html page of my web site there are three buttons.

网站中的三个按钮

After clicking these buttons, page re-direct to another page named productandservices.html. In their I show fishes for each selected category(when someone select Freshwater fish in index.html, it shows freshwater fishes in productandservices.html).

 <a href="servicesAndProduct.html"><button class="menu-buttons">FRESHWATER FISH</button></a> <a href="servicesAndProduct.html"><button class="menu-buttons">MARINE FISH</button></a> <a href="servicesAndProduct.html"><button class="menu-buttons">AQUA PLANTS</button></a>

Above you can see the three buttons in index.html. But after clicking these buttons, they only re-directing page. But do not show the selected category. To achieve that, What I can do in Java Script?

What I want is when someone click on Marine fish index.html, I want to show them Marine fish category in servicesandproduct.html

Don't really know how your code works in servicesAndProduct.html yet.

For now I assume that your page has static content. So you've all products over there like below. Let's say a div with the content of a product and each div had a few classes for styling, like product, the catecory and a class that hides the product by the default.

<div class="product marine-fish hidden"><!--product content--></div>
<div class="product marine-fish hidden"><!--product content--></div>
<div class="product aqua-plant hidden"><!--product content--></div>

This way you'll be able to select all elements with the class that belongs to the category you want to show and you just remove the hidden class. Then only those elements will be shown.

On your index page change the links as below:

<a href="servicesAndProduct.html?cat=freshwater-fish">
<a href="servicesAndProduct.html?cat=marine-fish">
<a href="servicesAndProduct.html?cat=aqua-plant">

On your servicesAndProduct.html you'll add some Javascript like

const parameters = new URLSearchParams(window.location.search);
const category = parameters.get("cat"); //now this says "freshwater-fish", "marine-fish" or "aqua-plant"


// In this example the only thing you need to do now is show all elements from this category
const elements = document.querySelectorAll("."+category);

elements.forEach(element => {
   element.classList.remove('hidden');
});

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