2014-11-02 180 views
6

我正在學習Express/Node/Jade,現在在Jade文件中我想包含來自公共文件夾的JavaScript文件,僅用於頁面。 例如,在玉文件I輸入:Jade:加載外部javascript和調用函數

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

和內部test.js我有一個函數

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

然後我嘗試

- 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只能被這個頁面使用。

回答

3

嗯......在第一個例子中,瀏覽器中發生的事情與服務器上發生的事情不同。所以如果你在瀏覽器中,Jade就是HTML的呈現。這就是ExpressJS的運送,即渲染翡翠。如果你想打電話,你的HTML Javascript(渲染翡翠),應該告訴你在哪裏的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」從不在服務器中運行。

1

或者把所有的文件夾在一個公共文件夾,例如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')

0

保存您的JS文件,並在你的玉鏈接它申報爲:

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

然後調用功能,我使用一個按鈕在此例如:

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