import and export a jquery function

2019-04-16 03:16发布

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条回答
爷、活的狠高调
2楼-- · 2019-04-16 03:41

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.

查看更多
登录 后发表回答