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

脚本问题:点击菜单实现元素显示/隐藏功能异常

Fixing the Show/Hide Menu Functionality

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 the active class 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

  1. 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.
  2. 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 (like active).
  3. Narrowed Selector Scope: Changed $('a') to $('a[class^="test"]') so we only target the menu links, not all links on the page.
  4. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:55:14