【问题标题】:Using jQuery in DOM manipulation of NodeJS-Express app在 NodeJS-Express 应用程序的 DOM 操作中使用 jQuery
【发布时间】:2020-03-19 01:31:02
【问题描述】:

我正在开发第一个 nodejs 应用程序,我需要使用 jquery 进行 DOM 操作。我通过 npm 安装了 bootstrap,我的浏览器报告 bootstrap.min.js 和 bootstrap.min.css 都已成功加载。

我在我的项目目录中执行npm i bootstrap。并使用 app.use(express.static(__dirname + '/node_modules/bootstrap/dist')); 在我的 js 文件中加载引导程序。

我在用来显示我的应用程序的把手脚本中包含了 bootstrap js 和 css。 css 生效并为我的应用程序设置样式,但我无法正确获取我的 jquery 代码。下面的代码是我的车把文件的内容:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <script language="javascript" src="js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="css/bootstrap.min.css"/>
</head>
<body>
    {{ my-content-outputing-here }}
</body>
</html>

<script type="text/javascript">
    $(body).hide();
</script>

<script>
    jquery(document).click(
        function(){
            alert( 'success' );
        }
    );
</script>

$jquery 无法识别并触发错误:

未捕获的引用错误:$ 未定义

虽然我了解问题所在,但我无法解决它。

更新:bootstrap/dist 的内容

node_modules/bootstrap/dist
├── css
│   ├── bootstrap-grid.css
│   ├── bootstrap-grid.css.map
│   ├── bootstrap-grid.min.css
│   ├── bootstrap-grid.min.css.map
│   ├── bootstrap-reboot.css
│   ├── bootstrap-reboot.css.map
│   ├── bootstrap-reboot.min.css
│   ├── bootstrap-reboot.min.css.map
│   ├── bootstrap.css
│   ├── bootstrap.css.map
│   ├── bootstrap.min.css
│   └── bootstrap.min.css.map
└── js
    ├── bootstrap.bundle.js
    ├── bootstrap.bundle.js.map
    ├── bootstrap.bundle.min.js
    ├── bootstrap.bundle.min.js.map
    ├── bootstrap.js
    ├── bootstrap.js.map
    ├── bootstrap.min.js
    └── bootstrap.min.js.map

【问题讨论】:

    标签: jquery node.js twitter-bootstrap


    【解决方案1】:

    您尚未在需要包含的标题部分添加 jQuery 脚本。

    <head>
        <meta charset='utf-8'>
        <meta http-equiv='X-UA-Compatible' content='IE=edge'>
        <title>Page Title</title>
        <meta name='viewport' content='width=device-width, initial-scale=1'>
        <link rel="stylesheet" href="css/bootstrap.min.css"/>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script language="javascript" src="js/bootstrap.min.js"></script>
    </head>
    

    您需要添加的。

    其次,您需要在执行 jQuery 代码之前让 DOM 准备就绪。

    $(document).ready(function() {
    
        $(document).click(
            function() {
                alert( 'success' );
            }
        );
    
    });
    

    【讨论】:

    • 谢谢。但是,我想在本地使用 jquery 而不是使用 CDN。我认为引导程序已经安装了 jquery 以在本地使用?我可以确认。我粘贴了我的引导模块的打印输出以确认 jquery 的存在
    • @sisko jQuery 不附带引导程序。需要通过npm i jquery或者CDN安装。
    猜你喜欢
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2016-08-31
    • 2019-05-29
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多