将JS分离为多个文件

Separating JS to multiple files

本文关键字:文件 JS 分离      更新时间:2023-09-26

我的web项目中有多个页面使用完全相同的JS函数。我将相同的函数复制并粘贴到所有页面的js文件中。但最近将公共函数分离到另一个名为common_fns.js的js文件中,对于每个页面,只创建选择器缓存的变量,并按some_page.jscommon_fns.js的顺序放置在每个页面的顶部。类似的东西

some_page.js

$(function() {
    var closer=$("#nlfcClose"),
    NewFormContainer=$("#NewLessonFormContainer"),
    opener=$("#nlfcOpen"),
    NewForm=$("#NewLessonForm"),
    OpsForm=$("#LessonOps"),
    SelectBox=$( "#courses" ),
    SelectBoxOptions=$("#courses option"),
    jquiBtn=$(".jquiBtn"),
    AddOp="AddLesson",
    DelOp="DelLesson";
});

common_fns.js

$(function() {
    SelectBoxOptions.text(function(i, text) {
        return $.trim(text);
    });
    SelectBox.combobox();
    jquiBtn.button();
    closer.button({
        icons: {
            primary: "ui-icon-closethick"
        },
        text: false
    }).click(function(){
        NewFormContainer.slideUp("slow");
    });
    opener.click(function(){
        NewFormContainer.slideDown("slow");
    });
    NewForm.submit(function(){
        var querystring = $(this).serialize();
        ajaxSend(querystring, AddOp);
        return false;
    });

    OpsForm.submit(function(){
        var querystring = $(this).serialize();
        ajaxSend(querystring, DelOp);
        return false;
    });
});

当我将通用函数复制并粘贴到每一页的文件中时,它就开始工作了。但现在它并没有:即使对于第一个函数,Firebug也会显示错误消息undefined SelectBoxOptions。我错过了什么?将相同的函数复制粘贴到每个页面的js文件中的唯一方法?

您在事件处理程序中声明局部变量,这就是为什么不能在下一个事件处理程序使用它们的原因。

声明函数外的变量:

var closer, NewFormContainer, opener, NewForm, OpsForm, SelectBox, SelectBoxOptions, jquiBtn, AddOp, DelOp;
$(function() {
    closer = $("#nlfcClose");
    NewFormContainer = $("#NewLessonFormContainer");
    opener = $("#nlfcOpen");
    NewForm = $("#NewLessonForm");
    OpsForm = $("#LessonOps");
    SelectBox = $( "#courses" );
    SelectBoxOptions = $("#courses option");
    jquiBtn = $(".jquiBtn");
    AddOp = "AddLesson";
    DelOp = "DelLesson";
});