VS Code中jQuery报错:Reference Error: $ not defined 求助
Fixing the "ReferenceError: $ is not defined" Issue
Hey, let's get this sorted out! The first and most obvious problem in your HTML code is a wrong attribute used to load your script.js file.
The Critical Mistake
You're using the href attribute for your script tag, but external JavaScript files need to be loaded with the src attribute. href is meant for link tags (like your CSS file), not script tags. That means your script.js might not be loading correctly, or it's trying to execute code before jQuery is properly accessible.
Here's the corrected line for your script tag:
<script type="text/javascript" src="script.js"></script>
Additional Checks to Ensure Everything Works
Even after fixing the attribute, here are a few more things to verify:
- Confirm jQuery is Loading: Test the jQuery CDN link directly in your browser to make sure it's accessible. If you run into issues with the CDN, try downloading jQuery locally and linking to the local file instead.
- Double-Check Load Order: Ensure your jQuery script tag comes before your
script.jstag (you already have this right in your code, but it's worth double-checking if you make edits later). - Check Browser Network Tab: Open your browser's developer tools (F12), go to the Network tab, and reload your page. Verify that both
jquery.min.jsandscript.jsload with a 200 OK status (no 404 errors). Ifscript.jsshows a 404, make sure the file path matches its location relative to your HTML file. - Avoid Library Conflicts: If you're using other libraries that might also use the
$symbol, wrap your jQuery code in a no-conflict wrapper to prevent clashes:jQuery(document).ready(function($) { // Your code here, using $ safely });
内容的提问来源于stack exchange,提问作者Kim Duclos
相关产品推荐
相关产品推荐

