首页 > 解决方案 > 在 expressJs 中堆栈 jquery

问题描述

我正在寻找一种从 express app.js 文件中堆叠 jquery 的方法。
也许这是不可能的,但我需要在app.js其中使用 jquery 来修改 html 文件。

例子:

应用程序.js

const express = require('express')
const app = express()
const $ = global.jQuery = require( 'jquery' );

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname+'/index.html'));
  $("#click").click(function(e){
        console.log('click');   
    }) 
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

索引.html

<!doctype html>
<html>
<head>
  <title>Express - Jquery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body> 
    <button id="click" type="button">Click</button>
</body>
</html>

也许我使用了错误的方法......
如果有人已经这样做了

标签: javascriptjquerynode.jsexpress

解决方案


此代码属于客户端,而不是服务器端

$("#click").click(function(e){
    console.log('click');   
})

你会把它放在你的index.html. (或在您的 . 引用的外部脚本中index.html。)例如:

<!doctype html>
<html>
<head>
  <title>Express - Jquery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body> 
    <button id="click" type="button">Click</button>
</body>
<script type="text/javascript">
    $("#click").click(function(e){
        console.log('click');
    });
</script>
</html>

服务器端代码没有浏览器内 DOM 的概念。它只是将页面作为对收到的 HTTP 请求的响应返回给客户端。该页面上的客户端 JavaScript 与浏览器中的 DOM 交互。


推荐阅读