将JS分离为多个文件

her*_*ron 2 javascript jquery selector domready

我的web项目有多个页面使用完全相同的JS功能.我正在复制并粘贴相同的功能到所有页面的js文件.但最近分隔常用功能到另一个名为js文件common_fns.js,用于创建只是选择缓存变量,并放置在每个页面,以便顶部的每一页some_page.js,common_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";
});
Run Code Online (Sandbox Code Playgroud)

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;
    });
});
Run Code Online (Sandbox Code Playgroud)

当我将常用功能复制并粘贴到每个页面的文件时,它正在工作.但现在它没有:Firebug undefined SelectBoxOptions即使对于第一个函数也显示错误消息.我错过了什么?只有这样才能将相同的功能复制粘贴到每个页面的js文件中?

Guf*_*ffa 5

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

声明函数外的变量:

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";
});
Run Code Online (Sandbox Code Playgroud)