import and export a jquery function

2019-04-16 03:12发布

问题:

I have a custom.js file with jquery code :

$('.nav.navbar-nav > li').on('click', function(e) {
$('.nav.navbar-nav > li').removeClass('active');
$(this).addClass('active');
});

I want to export this code to the main.js file.Both files are in the same folder.

Went through the documentation but couldn't understand how to do it with jquery.

回答1:

First you need to wrap this code in a function. Then you export the function. Finally you import it in main.js:

custom.js

export function foo () {
    $('.nav.navbar-nav > li').on('click', function(e) {
        $('.nav.navbar-nav > li').removeClass('active');
        $(this).addClass('active');
    });
}

main.js

import {foo} from 'custom'

foo();

ECMA SCRIPT 6 modules

Also notice that you need a module loader (like webpack/systemjs/requirejs etc.), as well as Babel that transpiles your ES6 code to ES5.