2

私のWebプロジェクトには、まったく同じJS関数で動作する複数のページがあります。すべてのページのjsファイルに同じ関数をコピーして貼り付けていました。しかし、最近、共通の関数を、という名前の別のjsファイルに分離しcommon_fns.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ファイルに同じ関数をコピーして貼り付ける唯一の方法は?

4

1 に答える 1

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";
});
于 2012-09-05T19:40:02.333 に答える