[英]I want to use JQuery in Node.js and EJS but $ is not defined
I want to use JQuery so I did like this. 我想使用JQuery,所以我这样做了。
But it still doesn't work. 但这仍然行不通。
and this is .ejs page 这是.ejs页面
<html>
<head>
<script src="/js/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<%
$(".btn").click(function(){
window.location.href = "/main";
});
%>
</head>
<body>
//display something
</body>
</html>
and this is app.js 这是app.js
var express = require('express');
var $ = require('jquery')(window);
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('ejs', require('ejs').renderFile);
var server = app.listen(8080);
app.use(express.static('public'));
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist'));
var router = require("./routes/index.js")(app);
the error code is, 错误代码是,
$ is not defined
how can I fix it? 我该如何解决?
I am personally of the opinion that jQuery is best handled on the client side - it's better for your server's performance, otherwise you will have to work with the DOM on the server side - which will use more server resource. 我个人认为jQuery最好在客户端上处理-更好地提高服务器的性能,否则您将不得不在服务器端使用DOM-它将使用更多的服务器资源。
However if you still want to use jQuery on the server side, then this link has a more complete guide: https://www.npmjs.com/package/jQuery 但是,如果您仍然想在服务器端使用jQuery,则此链接提供了更完整的指南: https : //www.npmjs.com/package/jQuery
It looks like you're requiring the wrong file, since javascript is case sensitive. 由于javascript区分大小写,因此您似乎需要使用错误的文件。
You're requiring jquery
when you want to be requiring jQuery
. 当您需要jquery
时,您需要使用jQuery
。 Try changing that. 尝试更改它。
It did like this. 它确实是这样。 node.js is so confusing. node.js是如此令人困惑。 thank you so much. 非常感谢。
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
$(".btn").click(function(){
window.location.href = "/main";
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.