简体   繁体   中英

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

I'm still new to Node.js, but I'll try to explain my problem as good as I can.

So I'm working on a movie site to practice my node.js/express skills a bit and I use the following elements (img) on basically every page of my website:

Header with stats and search input and a navigation bar (will be reused on every page)

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

The follow JS-code are two examples of actions on the client side that I use to navigate to other web pages, this then activates GET on the client side.

$(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);
    })
});

I want this to be the same code on every page. I could type the same code every time, but that would be a waste of time.For HTML and CSS I am able to use templates (HTML) or import other CSS files to save time. Is there something similar for JS on the client side?

Put that code in a file, for example "navigator.js" and then load it in your html header in every page you want to use it

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>

Finally i suggest you to assign an id to your button, for example "searchButton" instead only "button"

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM