问题
I have this error message ReferenceError: $ is not defined when using vscode built-in debugger node.js Here is the html
<!doctype html>
<html lang="en">
<head>
<title>14. Getting Started with jQuery</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
Here is the app.js
$(function() {
// start up code goes here
alert("this works!");
});
I put a breakpoint at the alert line and run the debug (node.js) in vscode. It stopped at $(function() { - the first line of app.js with error message of ReferenceError: $ is not defined. Seems like jQuery is not loaded.
I tried
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
and
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
but none of them works. Please help.
回答1:
If you want to use the jQuery loaded in your HTML file in NodeJS, you need to associate it with $
first:
Go to the script where you want to use it, and write:
window.$ = window.jQuery;
If that does not work, install the jQuery npm package by opening your terminal inside the folder of your script and then typing:
npm i jquery
Then write
window.$ = window.jQuery = require("jquery");
in your script.
来源:https://stackoverflow.com/questions/48457867/referenceerror-is-not-defined-when-debug