0

イベントが発生し、変数にアクセスしようとしている関数の内部にあるにもかかわらず、を取得しUncaught TypeError: Cannot read property '...' of undefinedます。だから、言いましょう:

( function($) {

    $.fn.main = function() {

        this.setting = 1;

        $("#someElement").scroll( function() {

            console.debug(this.setting);

        } );

    }

} )(jQuery);

タイミングと関係があると思いますが、やはり間違っているかもしれません。コピーをthis作成して公開する必要がありますか?誰?ありがとう。

4

4 に答える 4

3

はその値を動的に取得するため、の値をクロージャに固定することはthisできません。this

試す :

var self = this;

そして、自己を参照します。

于 2012-04-12T08:52:10.780 に答える
1

this別の変数にコピーするだけ です

( function($) {

    $.fn.main = function() {

        this.setting = 1;
        var that = this;
        $("#someElement").scroll( function() {

            console.debug(that.setting);

        } );

    }

} )(jQuery);
于 2012-04-12T08:52:54.647 に答える
0
( function($) {

    $.fn.main = function() {

        this.setting = 1; // "this" refers to the "$.fn.main" object

        $("#someElement").scroll( function() {

            console.debug(this.setting); // "this" refers to the "$('#someElement')" object

        } );

    }

} )(jQuery);

thisfromを使用する場合は$.fn.main、変数を格納できます。次のように動作します。

( function($) {

    $.fn.main = function() {

        var that = this

        that.setting = 1; // "this.setting" would also work

        $("#someElement").scroll( function() {

            console.debug(that.setting); // You need to reference to the other "this"

        } );

    }

} )(jQuery);
于 2012-04-12T08:55:06.050 に答える
0

スクロールメソッドのthis内部はスクロールメソッドを参照しています。このメソッドは、ID が「someElement」の要素のスクロール イベントで呼び出されるようにバインドされています。バインディング オブジェクトのスコープは失われます。

于 2012-04-12T09:18:30.600 に答える