javascript - 在客户端重用 JavaScript 代码(node.js、express)

标签 javascript node.js express client

我对 Node.js 还很陌生,但我会尽力解释我的问题。

因此,我正在一个电影网站上工作,以练习一下我的 node.js/express 技能,并且我基本上在网站的每个页面上都使用以下元素 (img):

带有统计信息和搜索输入的标题以及导航栏(将在每个页面上重复使用)

header with stats and search input and a navigation bar that will be reused on every page

下面的 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 header 中

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”

希望这有帮助

关于javascript - 在客户端重用 JavaScript 代码(node.js、express),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46333920/

相关文章:

javascript - 如何使用javascript制作多个计数器?

javascript - 如何使用loopback api和angularjs检索最新创建的记录

node.js - 更新 Mongoose 中的对象会导致循环

javascript - Node.js - 让 Node.js/Express 与 Web 音频 API 配合使用

node.js - 有没有办法用restify在控制台中记录每个请求?

javascript - 环境设置 egghead.io 教程?

javascript - 单击两者时,下一个和上一个按钮不起作用

javascript - Node.js + Mongoose 中的基本建模

javascript - 如何在 Express.js 中为路由的子路径呈现不同的 View ?

node.js - Node/Express 角度 5 路由