如何修改结账页面Next按钮的隐藏逻辑并实现代码定时执行?
Let's tweak your code to meet both requirements smoothly: keeping the "next" button visible when "session 5 of 5" is in the cart, and making the logic run continuously to adapt to in-page navigation changes.
Step 1: Refine the Detection Logic
We need to add a critical check for "session 5 of 5" — if this session exists in the cart, we should never hide the "next" button, even if the other partial sessions are present. The updated rule becomes: hide the button only if any of sessions 1-4 are present and session 5 is not in the cart.
Step 2: Add Continuous Execution
Wrap the core logic in a reusable function, then use setInterval() to run it at regular intervals (we'll use 3 seconds as a default, but you can adjust this). We'll also run the function once immediately when the page loads so the button state is correct right away, no waiting required.
Here's the modified, fully functional code:
// Define the sessions we need to check const partialSessions = ["session 1 of 5", "session 2 of 5", "session 3 of 5", "session 4 of 5"]; const completeSession = "session 5 of 5"; // Core function to update the next button's visibility function adjustNextButton() { const cartContent = $(".bookly-cart-step").text(); // Check if any partial session is present const hasPartial = partialSessions.some(session => cartContent.includes(session)); // Check if the complete 5th session is present const hasComplete = cartContent.includes(completeSession); // Update button class: hide only if partial sessions exist AND no complete session if (hasPartial && !hasComplete) { $(".bookly-next-step").addClass("hideElement"); } else { // Ensure the button becomes visible again if conditions change $(".bookly-next-step").removeClass("hideElement"); } } // Run once immediately on page load to set initial state adjustNextButton(); // Run every 3 seconds (3000ms) to handle in-page navigation updates setInterval(adjustNextButton, 3000);
Quick Explanations:
- Switched to
includes()instead ofindexOf() >= 0for cleaner, more readable code (it works exactly the same way). - Added
removeClass()to reverse the hiding action if the cart updates to include session 5, or removes the partial sessions. - The interval time (3000ms) is adjustable — if you need more frequent checks, lower the number (e.g., 2000 for 2 seconds), but avoid setting it too low to prevent unnecessary performance overhead.
内容的提问来源于stack exchange,提问作者Matt Cooper

