多按钮对应多div的Show More/Less功能JavaScript逻辑问题排查
I see you're having trouble getting multiple "Show More/Less" buttons to properly toggle their corresponding content divs—let's fix that! The core issues in your original code were targeting the wrong elements and overwriting classes instead of toggling them. Here's the step-by-step solution:
What Was Wrong?
- You were targeting all
.show-less-contentelements at once instead of the specific one linked to the clicked button - Overwriting the
classNameproperty erased the base.show-less-contentclass, breaking your default styling - No proper way to map each button to its adjacent content div
Corrected Code
First, keep your existing CSS (it's working fine):
.show-less-content { min-width: 100%; width: 100%; background: #fff; padding: 0px; padding-top: 0; font-family: calibri; font-size: 18px; color: #444; margin: 0; max-height: 105px; overflow: hidden; -webkit-transition: max-height 0.7s; -moz-transition: max-height 0.7s; transition: max-height 0.7s; } .open{ max-height: 100%; -webkit-transition: max-height 0.7s; -moz-transition: max-height 0.7s; transition: max-height 0.7s; }
Now update your JavaScript to properly link each button to its content:
if (document.readyState == 'loading') { document.addEventListener('DOMContentLoaded', ready) } else { ready() } function ready() { const showButtons = document.getElementsByClassName("show-more"); // Use let instead of var to avoid closure issues in loops for (let i = 0; i < showButtons.length; i++) { showButtons[i].addEventListener('click', function(event){ const button = event.target; // Grab the content div directly before the clicked button const content = button.previousElementSibling; // Toggle the 'open' class without removing base styles content.classList.toggle('open'); // Update button text based on the content's current state button.innerHTML = content.classList.contains('open') ? "Show Less" : "Show More"; }) } }
Your PHP code doesn't need any changes—it correctly generates paired content divs and buttons for each menu item.
Key Improvements
- Target Specific Content:
button.previousElementSiblingensures each button only interacts with its immediate adjacent content div, no more cross-talk between elements. - Safe Class Toggling:
classList.toggle('open')adds or removes the expand class without overwriting the base.show-less-contentstyles, keeping your default layout intact. - Simplified State Checks: Using a ternary operator makes the button text update concise and easy to read.
- Closure Bug Fix: Switching to
letfor the loop index ensures each event listener references the correct button in the loop.
Test this out—each button should now smoothly expand/collapse its corresponding content, with the button text updating accurately every time.
内容的提问来源于stack exchange,提问作者Eduard Tester

