【问题标题】:Jade: load external javascript and call functionJade:加载外部javascript并调用函数
【发布时间】:2014-12-29 09:17:18
【问题描述】:

我正在学习 Express/Node/Jade,现在我想在 Jade 文件中包含一个来自公共文件夹的 javascript 文件,仅用于页面。 例如,在翡翠文件中,我输入:

script(src='/javascripts/test.js')

在 test.js 里面我有一个函数

function check_test(){
    return "It's working!"
}

然后我尝试调用 Jade by 中的函数

- var test_response = check_test()

我得到的错误是“未定义不是函数”并且 test.js 根本没有加载。 显然 Jade 不会加载文件,它们只会转换为 HTML 代码。

我看了别人的问题,这是我能找到的最接近的问题,但它没有提供明确的答案。 In Jade, how can you call a function in an external Javascript

所以我的问题是:在这种情况下,我应该怎么做才能让它发挥作用?

我不想在 layout.js 中加载文件,因为我只希望 test.js 仅被此页面使用。

【问题讨论】:

    标签: javascript node.js express pug


    【解决方案1】:

    嗯...首先,在浏览器中发生的事情与在服务器上发生的事情是不同的。所以 Jade 是 HTML 的渲染,因此如果你在浏览器中。它是 ExpressJS 所提供的,即渲染 Jade。如果你想调用,你的 HTML Javascript (Rendering of Jade),应该告诉你 Javascript 在哪里。例如

    在 Server.js 中

    // Get the Javascript in the browser
    app.use("/javascripts", express.static("./outJavascripts"));
    // Get the URL
    app.all("/", function(req, res){
      // Render the Jade and Send for the client (Browser)
      req.render("myTemplate.jade");
    });
    

    在 myTemplate.jade 中

    script(src='/javascripts/test.js')
    

    在“./outJavascripts/test.js”中

    function check_test(){
        console.log("It's working! :D");
        return "It's working!";
    }
    

    如果你这样做,你会意识到它正在运行,浏览器中的文件“./outJavascripts/test.js”。并且“check_test”函数永远不会在服务器中运行。

    【讨论】:

      【解决方案2】:

      或者将所有文件夹放在一个公共文件夹中,例如public

      public -javascripts -stylesheets -images

      然后公开该公用文件夹

      app.use(express.static(path.join(__dirname, 'public')));

      这意味着你可以

      script(src='/javascripts/script.js') link(rel='stylesheet', href='/stylesheets/style.css')

      【讨论】:

        【解决方案3】:

        保存您的 JS 文件并将其链接到您的 Jade 文件中:

        script(src="filepath/yourJSfile.js")
        

        然后调用函数,我这里用一个按钮举例:

        button(class="btn", onclick='functionName()')
        

        【讨论】:

          猜你喜欢
          • 2019-03-12
          • 2018-04-22
          • 2013-01-12
          • 1970-01-01
          • 1970-01-01
          • 2013-01-22
          • 2014-10-01
          • 2015-03-02
          • 2019-12-13
          相关资源
          最近更新 更多