You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery中实现页面跳转后执行代码并显示对应内容

Solution: Filter Product Page Content When Navigating from Home

Got it, let's sort this out! The problem you're facing makes total sense—when you redirect to a new page, the JavaScript running on your home page can't interact with elements on the product page. They're separate page loads, so any code from the home page stops executing once the redirect happens. We need to pass a little piece of information from the home page to the product page, then use that info on the product page to show only the right item.

Here's how to fix it step by step:

Step 1: Pass the selected fruit as a URL parameter from the home page

Instead of just redirecting to product.html, we'll add a query parameter to the URL that tells the product page which fruit was selected. Update your home page's jQuery code like this:

$(document).ready(() => {
  $('#hpbanana').on('click', () => {
    window.location.replace("product.html?fruit=banana");
  });

  $('#hpblueberry').on('click', () => {
    window.location.replace("product.html?fruit=blueberry");
  });

  $('#hpbayabas').on('click', () => {
    window.location.replace("product.html?fruit=bayabas");
  });
});

Step 2: Read the parameter and filter items on the product page

Now, on the product page, we'll read that URL parameter and use it to hide all items except the selected one. Add this code to your myjquery.js file (it will run when the product page loads):

$(document).ready(() => {
  // Helper function to grab query parameters from the URL
  function getSelectedFruit() {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('fruit');
  }

  const selectedFruit = getSelectedFruit();
  
  if (selectedFruit) {
    // Hide all product items first
    $('.list-group-item').addClass('hide');
    // Show only the item matching the selected fruit
    $(`#pp${selectedFruit}`).removeClass('hide');
  }
  // If no parameter exists (user visited product page directly), show all items
});

Why this works

  • When you click a button on the home page, the URL now includes something like ?fruit=banana—this is our way of telling the product page what to show.
  • When the product page loads, we check for that parameter. If it exists, we hide all items and only show the one that matches the parameter (using the ID pattern you already have: pp + fruit name).
  • If someone visits the product page directly (without coming from the home page), all items stay visible, keeping your default behavior intact.

Just double-check that your .hide CSS class is still set to display: none;—you already have that, so you're good to go!

内容的提问来源于stack exchange,提问作者Greg Vestil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:54:45