1

選択メニュー ハンドラー内の選択メニューの選択値に変数を設定しようとしています。問題は、選択ハンドラーのコンテキスト内で変数が認識されず、選択ハンドラーに変数コンテキストを渡すと、選択した変数の値にアクセスできなくなることです。回避策を知っている人はいますか?

function object(){
    this.testVar;
    this.handler;
}

function makeObject(){
    var result = new object();
    result.testVar;
    result.handler = handler;
    return result;
}

function handler(){
   alert($(this).val());
   alert(this.testVar);
    //ultimately this is what I want to do
    this.testVar = $(this).val();
}

//If I do it this way $(this).val() is defined but not testVar
$("#test-select").on("change", {
        testdata: this.testVar
    }, this.handler);

//If I do it this way testVar is defined but not $(this).val()
$("#test-select").on("change", {
        testdata: this.testVar
    }, $.proxy(this.handler,this));
4

1 に答える 1

1

ハンドラーを実行するコンテキストを決定し、他のコンテキストをパラメーターとしてハンドラー関数に渡す必要があります。

ハンドラーが呼び出されると、「this」は最初に変更された HTML 要素を参照します。リスナーを設定する場合、「this」はそれを設定するオブジェクトを参照します。

一例は次のとおりです。

function handler(obj) {
    alert($(this).val()); // this is the test-select object.
    alert(obj.testVar);
}

var self = this;
$("#test-select").on("change", {
    testdata: this.testVar
}, function() { self.handler(self); });
于 2013-01-13T07:51:18.860 に答える