将JS分离为多个文件

时间:2012-09-05 19:35:10

标签: javascript jquery selector domready

我的网络项目中有多个页面使用完全相同的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文件中?

1 个答案:

答案 0 :(得分: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";
});
相关问题