脚本问题:点击菜单实现元素显示/隐藏功能异常
Hey there! Let's work through the issues with your menu's show/hide feature and get it running smoothly.
Key Problems in Your Current Code
- DOM Loading Timing: The initial hide logic and click event bindings run before the DOM is fully ready, which can lead to elements not being found correctly.
- Fragile Number Extraction: Using
this.className.replace('test', '')fails if the element has multiple classes (like theactiveclass you add later), resulting in invalid selector strings. - Overly Broad Active Class Handling: Your current code targets all
<a>tags on the page, which might affect other links you don't want to modify.
Fixed Code
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="test3" href="#">> test</a> <div id="answer3"> <div class="center"> <p>hello</p> </div> </div>
JavaScript
$(document).ready(function(){ // Initialize all answer sections as hidden $('[id^="answer"]').hide(); // Bind click event only to .test* links $('a[class^="test"]').on('click', function(e){ e.preventDefault(); // Extract the number correctly using regex to avoid class conflicts var numb = this.className.match(/test(\d+)/)[1]; // Hide all answers first, then show the matching one $('[id^="answer"]').hide(); $('#answer' + numb).show(); // Update active class right here to keep related logic together $('a[class^="test"]').removeClass("active"); $(this).addClass("active"); }); });
What Changed & Why
- Wrapped Everything in
$(document).ready(): Ensures all code runs only after the DOM is fully loaded, so elements are always available when we try to interact with them. - Used Regex for Number Extraction:
this.className.match(/test(\d+)/)[1]reliably pulls out the numeric part from the class, even if there are other classes present (likeactive). - Narrowed Selector Scope: Changed
$('a')to$('a[class^="test"]')so we only target the menu links, not all links on the page. - Combined Active Class Logic: Moved the active class handling into the same click event handler, keeping related functionality grouped together for better readability and maintainability.
内容的提问来源于stack exchange,提问作者Tweak
相关产品推荐
相关产品推荐

