【问题标题】:I'm trying to run a jQuery code to change the h1 color based on whether it's a weekday or a weekend我正在尝试运行 jQuery 代码来根据是工作日还是周末来更改 h1 颜色
【发布时间】:2022-01-11 10:58:40
【问题描述】:

我正在尝试运行一个 jQuery 代码来根据是工作日还是周末来更改 h1 颜色 我不断收到的错误是“ReferenceError: $ is not defined”,有人可以帮我吗? app.js 位于 parentfolder/app.js 而 lists.ejs 位于 parentfolder/views/lists.ejs . document.queryselector 也不工作

app.js

const express = require("express");
const bodyPareser = require("body-parser");

const app = express();

app.use(bodyPareser.urlencoded({extended : true}));

app.set("view engine", "ejs");

app.get("/", function(req, res) {
    var date = new Date();
    var currentDay = date.getDay();

    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    if (currentDay === 0 || currentDay === 6) { 
        $(h1).style.color = "red";
    } else {
        $(h1).style.color = "blue";
    }
    res.render("lists", {today : days[currentDay]});

    res.sendFile(__dirname + "/views/lists.ejs");
});

app.listen("3000", function() {
    console.log("Server started in 3000");
});

lists.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Today is <%= today %></h1>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="app.js"></script>
</body>
</html>

【问题讨论】:

  • 很确定 app.js 将无法编译。 app.js 是服务端的后端逻辑,$(h1) 会报错

标签: javascript html jquery express ejs


【解决方案1】:

当您使用 Node 时,您正在运行服务器端(要使用需要它的库),您也不能使用客户端选择器,因为它们不存在

app.js

app.get("/", function(req, res, next) {
  const date = new Date();
  const currentDay = date.getDay();
    
  const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  let day_color
  if (currentDay === 0 || currentDay === 6) { 
     day_color = "red";
  } else {
     day_color = "blue";
   }
   res.render("lists", {today : days[currentDay],color:day_color},
     (err,html) => {
       if(err){
        console.log(err)
        return next(err)
       }
       res.send(html)
     })

});

list.ejs

<h1 <%= `style=color:${color}`%> >Today is <%= today %></h1>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多