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

AJAX页面回退/前进后点击按钮无法更新#filtered_posts问题求助

Alright, let's fix these two issues for you step by step—they're both related to how you're managing history states and updating the DOM based on the current page context.

Problem Breakdown

First, let's understand why your current code is misbehaving:

  1. Filter buttons stop working after back/forward:

    • Your global value variable is only updated when clicking navigation links, not filter buttons. So when the filter AJAX completes, ajaxComplete pushes the old navigation URL to history instead of a filter-specific URL. This desyncs the URL from the actual page state, causing subsequent filter clicks to only update the URL without changing content.
    • You’re using a single ajaxComplete handler for all AJAX requests, which leads to unpredictable history state pushes.
  2. No distinction between homepage and other pages:

    • Your popstate handler always replaces the entire .main content, even on the homepage where you only need to update #filtered_posts. This overwrites the DOM context needed for filter buttons to work correctly.

Fixed Code

Here's the revised code with explanations below:

$(document).ready(function () { 
    var $mainContent = $(".main"); 
    var $filteredPosts = $("#filtered_posts");
    // Get your homepage base URL (adjust if your homepage isn't the root)
    var baseHomeUrl = window.location.origin + window.location.pathname;

    // Navigation link handler (for non-homepage pages)
    $(document).on("click", "nav li a", function (e) { 
        e.preventDefault(); 
        const targetUrl = $(this).attr("href"); 
        
        $mainContent.load(targetUrl + " .main", function (loadedContent) { 
            const pageTitle = $(document).find("h1.entry-title").text();
            // Push state with clear target and content
            window.history.pushState({
                targetElement: ".main",
                content: loadedContent
            }, pageTitle, targetUrl);
        }); 
    }); 

    // Category filter handler (homepage only)
    $(document).on("click", "#category-filter li.filter-button", function (e) { 
        e.preventDefault(); 
        const category = $(this).data("category"); 
        const filterUrl = `${baseHomeUrl}?category=${category}`; // Build filter-specific URL

        $.post(wp_ajax.ajax_url, { action: "filter", category: category }, function (responseData, status) { 
            if (status === "success") { 
                $filteredPosts.html(responseData);
                // Push filter-specific state
                const filterTitle = `Category: ${category}`; // Customize title as needed
                window.history.pushState({
                    targetElement: "#filtered_posts",
                    content: responseData
                }, filterTitle, filterUrl);
            } else { 
                console.warn("Filter request failed:", responseData); 
            } 
        }); 
    }); 

    // Popstate handler: Update the correct element based on state
    window.addEventListener('popstate', function (event) { 
        if (!event.state) {
            // Fallback to initial homepage state if no state exists
            $mainContent.load(baseHomeUrl + " .main");
            return;
        }

        // Target the correct element from the state data
        const $target = $(event.state.targetElement);
        if ($target.length) {
            $target.html(event.state.content);
        }
    }); 

    // Initialize initial page state (so first back/forward works correctly)
    const initialTarget = $filteredPosts.length ? "#filtered_posts" : ".main";
    const initialContent = $filteredPosts.length ? $filteredPosts.html() : $mainContent.html();
    const initialTitle = $(document).find("h1.entry-title").text();
    window.history.replaceState({
        targetElement: initialTarget,
        content: initialContent
    }, initialTitle, window.location.href);
});

Key Improvements Explained

  1. Removed global state variables:

    • No more relying on a shared value variable that gets out of sync. Each action (navigation/filter) explicitly defines its own URL and state data.
  2. Context-aware history states:

    • Navigation clicks push states targeting .main, while filter clicks push states targeting #filtered_posts. This tells the popstate handler exactly which element to update.
  3. Filter URL synchronization:

    • Filter clicks now build a proper URL with a category parameter, so the browser address bar matches the current filter state.
  4. Targeted DOM updates:

    • The popstate handler checks the state's targetElement to decide whether to update .main (other pages) or #filtered_posts (homepage), avoiding unnecessary DOM overwrites.
  5. Initial state setup:

    • We use replaceState to set the initial page state on load, so the first back/forward action doesn't leave you with a blank page.

Testing Tips

  • After applying this code:
    1. Click a filter button—verify the URL updates and #filtered_posts content changes.
    2. Use the back button—confirm only #filtered_posts reverts to its previous state.
    3. Navigate to another page via the nav, then use forward/back—verify .main updates correctly.
    4. After navigating back to the homepage, click a filter button again—ensure content updates and history works as expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 21:12:56