繁体   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