HTML+JQuery点击事件失效求助:响应式网站菜单切换异常
Hey there! Let's work through why your menu toggle click event isn't firing properly. Looking at your code, there are a few clear issues that are blocking the functionality:
Key Problems in Your Code
- No target element for
toggleClass: Right now, your$toggleClass('collapse')line doesn't specify which element should get the class toggled. jQuery has no idea which element to modify here! - Undeclared variable: You're using
$toggleCollapsewithout declaring it withvar,let, orconst. This creates a global variable which can lead to unexpected behavior down the line. - Possible missing jQuery library: If you haven't loaded the jQuery library on your page before your custom script, none of your jQuery code will run at all.
Corrected Code Example
First, make sure you're targeting the right menu container element (replace .menu-container with your actual menu's selector). Here's the fixed jQuery:
$(document).ready(function(){ const $toggleCollapse = $('.toggle-collapse'); // Replace with your actual menu container selector const $menuContainer = $('.menu-container'); $toggleCollapse.click(function(){ $menuContainer.toggleClass('collapse'); }); });
And keep your existing CSS as is:
.collapse { height: 30rem; }
Quick Checks to Ensure It Works
- Verify selectors are correct: Add
console.log($toggleCollapse.length)inside thereadyfunction. If it outputs0, your.toggle-collapseselector isn't matching any element on the page—double-check your HTML classes. - Confirm jQuery is loaded: Make sure you have a script tag loading jQuery before your custom script, like:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script src="your-custom-script.js"></script> - Check CSS targeting: Ensure the
.collapseclass is being applied to the element you want to resize (your menu container), not the toggle button itself.
内容的提问来源于stack exchange,提问作者NelsonVasu
相关产品推荐
相关产品推荐

