簡體   English   中英

在客戶端重用javascript代碼(node.js,快速)

[英]Reuse javascript code on client side (node.js, express)

我仍然不熟悉Node.js,但我會盡力解釋我的問題。

因此,我正在電影網站上工作,以練習我的node.js / express技能,並且基本上在我網站的每個頁面上都使用以下元素(img):

具有統計信息和搜索輸入的標題以及一個導航欄(將在每個頁面上重復使用)

具有統計信息和搜索輸入的標題以及將在每個頁面上重復使用的導航欄

以下JS代碼是客戶端上用於導航到其他網頁的兩個動作示例,然后在客戶端上激活GET。

$(function () {

    $('button').click(function (event) {
        event.preventDefault()
        // the value people enter in the search box

        var search = $('.searchInput').val();

        //replace spaces with _
        var res = search.replace(/\s/g, "_");

        //build the URL
        var link = window.location.protocol + '//' + window.location.host + '/search/' + res;

        // redirect to trigger GET in indexjs with specific search value
        window.location.replace(link);

        });

    $('.lists').click(function (event) {
        var link = window.location.protocol + '//' + window.location.host + '/lists/topAll';
        window.location.replace(link);
    })
});

我希望每個頁面上的代碼都一樣。 我每次都可以輸入相同的代碼,但這會浪費時間。對於HTML和CSS,我可以使用模板(HTML)或導入其他CSS文件來節省時間。 客戶端的JS是否有類似的東西?

將該代碼放入文件中,例如“ navigator.js”,然后將其加載到要使用它的每個頁面的html標頭中

navigator.js:

$(function () {

    $('button').click(function (event) {
        event.preventDefault()
        // the value people enter in the search box

        var search = $('.searchInput').val();

        //replace spaces with _
        var res = search.replace(/\s/g, "_");

        //build the URL
        var link = window.location.protocol + '//' + window.location.host + '/search/' + res;

        // redirect to trigger GET in indexjs with specific search value
        window.location.replace(link);

        });

    $('.lists').click(function (event) {
        var link = window.location.protocol + '//' + window.location.host + '/lists/topAll';
        window.location.replace(link);
    })
});

的index.html

<script src="navigator.js"></script>

最后,我建議您為按鈕分配一個ID,例如“ searchButton”而不是“ button”

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM