【问题标题】:How do I include jQuery code in my node.js web app?如何在我的 node.js Web 应用程序中包含 jQuery 代码?
【发布时间】:2016-02-29 13:25:34
【问题描述】:

所以我一直在使用 node.js 开发一个(相当简单的)RESTful 应用程序,我已经完成了最后一点,现在唯一缺少的是使用 jQuery 来操作 html 页面,所以我可以编辑 html 的内容 - 这让我非常生气。

我学习了 try.jquery.com 教程,非常顺利;我绝不会称自己为 jquery 大师,但我在编写基本 html 操作的代码时几乎没有遇到什么麻烦,除了我从未真正考虑过 jquery 代码的去向。我尝试了很多不同的东西,但只有一种(真的很不方便)有效,所以我想知道是否可以澄清一下。

(注意:所有的js文件都在根目录下,index.html在root/public下;而我基本上只是通过npm/package.json运行app.js)

我已经尝试过在 app.js 主文件中包含 jQuery 代码:

app.js

//some imports/requires here
var $ = require('jquery');
//more imports/requires here

//error; document is undefined
$(document).ready($('h1').text('Im Here');

app.get('/', function (req, res) {

    res.sendFile(__dirname+'/public/index.html');

});

index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <title>Inspiratorator</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script="../app.js"></script>

我已经尝试在自己的文件中包含 jQuery 代码(尝试让代码位于 js 文件中,并尝试将代码导出为函数并从 app.js 调用它 -两者都没有做任何事情):

jusQueryin.js

var $ = require('jQuery'); //tried with and without this

$(document).ready(function () {
    $(' button ').on( 'click', $('h1').text("I'm here") );
    console.log('kpa'); 
});

index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <title>Inspiratorator</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script="../jusQueryin.js"></script>

我也尝试过(这行得通,但我不知道如何处理其他 .js 文件中的代码,如果可能的话):

index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <title>Inspiratorator</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script>
        $(document).ready(function () {
        $(' button ').on( 'click', $('h1').text("I'm here") );
        console.log('kpa'); 
    });
</script>

我也尝试了不同的变体(例如,在函数中包含(或不包含)就绪函数的第二部分,在 dom.ready 函数中使用 onClick 事件等),但唯一有效的变体是最后一种方法

理想情况下,我希望能够在 app.js 中使用 jQuery 代码,不太理想的是在它自己的文件中;或者如果我出于某种原因必须将它包含在 html 文件中,我至少需要能够与脚本块中的代码进行通信,以便我可以从数据库中获取信息等等。

【问题讨论】:

标签: javascript jquery html node.js


【解决方案1】:

记住一件事 jQuery 需要一个窗口对象才能工作。 jquery 的第一个功能是作为 dom 查询,dom 在窗口对象中。因此,您必须加载 jquery 并将其附加到窗口对象。

作为节点应用程序,您将拥有一个浏览器窗口作为应用程序的视图。尝试从CDN 将 jquery 添加到该窗口,在那里添加您的需求,瞧,现在包含 jquery 的包含范围(窗口),因为全局也将它传递给新需要的文件。

Error: jQuery requires a window with a document

index.html

 <script>
        window.$ = window.jQuery = require('./node_modules/jquery');
  </script>
  <script>
        var UI = require('./controllers/UI');
        UI.init(window);
  </script>

现在 var UI,在我的例子中是一个模块,包含

【讨论】:

  • 我不认为我关注
  • 只需在索引 html 中加载 jquery。然后需要你想使用 jquery 的模块,然后你就拥有了它,你只需配置你的模块以便它可以获取一些参数,然后你将 jquery 传递给它。所以需要 jquery,需要模块,传递参数,如 MyModule(window.$) - (我们将 jquery 传递给模块),然后你可以在你的模块下使用 jquery。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多