ReferenceError: $ is not defined when debug

自闭症网瘾萝莉.ら 提交于 2021-02-07 20:48:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!