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:
Filter buttons stop working after back/forward:
- Your global
valuevariable is only updated when clicking navigation links, not filter buttons. So when the filter AJAX completes,ajaxCompletepushes 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
ajaxCompletehandler for all AJAX requests, which leads to unpredictable history state pushes.
- Your global
No distinction between homepage and other pages:
- Your
popstatehandler always replaces the entire.maincontent, even on the homepage where you only need to update#filtered_posts. This overwrites the DOM context needed for filter buttons to work correctly.
- Your
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
Removed global state variables:
- No more relying on a shared
valuevariable that gets out of sync. Each action (navigation/filter) explicitly defines its own URL and state data.
- No more relying on a shared
Context-aware history states:
- Navigation clicks push states targeting
.main, while filter clicks push states targeting#filtered_posts. This tells thepopstatehandler exactly which element to update.
- Navigation clicks push states targeting
Filter URL synchronization:
- Filter clicks now build a proper URL with a
categoryparameter, so the browser address bar matches the current filter state.
- Filter clicks now build a proper URL with a
Targeted DOM updates:
- The
popstatehandler checks the state'stargetElementto decide whether to update.main(other pages) or#filtered_posts(homepage), avoiding unnecessary DOM overwrites.
- The
Initial state setup:
- We use
replaceStateto set the initial page state on load, so the first back/forward action doesn't leave you with a blank page.
- We use
Testing Tips
- After applying this code:
- Click a filter button—verify the URL updates and
#filtered_postscontent changes. - Use the back button—confirm only
#filtered_postsreverts to its previous state. - Navigate to another page via the nav, then use forward/back—verify
.mainupdates correctly. - After navigating back to the homepage, click a filter button again—ensure content updates and history works as expected.
- Click a filter button—verify the URL updates and
内容的提问来源于stack exchange,提问作者Techie
相关产品推荐
相关产品推荐

