2

javascriptプロトタイプクラスを作成しました。

メソッド内でjqueryクリックを作成します。しかし、このクリックの中で、ビルド関数を実行したいと思います。

jqueryクリック内でプロトタイプ関数を実行しようとすると、jqueryがこれを他の目的で使用するため、失敗します。

いろいろ試してみましたが、うまくいきませんでした。

Game.prototype.clicks = function(){
    $('.flip').click(function(){

        if(cardsPlayed.length < 2) //minder dan 2 kaarten gespeeld
        {
            $(this).find('.card').addClass('flipped');
            cardsPlayed.push($(this).find('.card').attr('arrayKey'));

            console.log(cardsPlayed[cardsPlayed.length - 1]);

            console.log(playingCards[cardsPlayed[cardsPlayed.length - 1]][0]);

            if(cardsPlayed.length == 2)// two cards played
            {
                if(playingCards[cardsPlayed[0]][0] == playingCards[cardsPlayed[1]][0])
                { // same cards played
                    console.log('zelfde kaarten');
                    playingCards[cardsPlayed[0]][0] = 0; //hide card one
                    playingCards[cardsPlayed[1]][0] = 0; //hide card two
                    //rebuild the playfield
                    this.build(); //error here
                }
                else
                {
                    //differend cards
                }

            }
        }

        return false;
    }).bind(this);
}
4

3 に答える 3

3

this問題は、クリックされた.flip要素とのオブジェクトを参照しようとしていることです。二重人格を持つことはできないため、これらの参照の 1 つを変更する必要があります。$(this).find('.card') Gamethis.build()this

最も簡単な解決策は、Licson によって既に提案されているように、オブジェクトを指す変数をハンドラーGameのスコープ内に保持することです。click次に、thisクリックされた要素のハンドラー内で (通常の jQuery ハンドラーと同様に) を使用selfし、Gameオブジェクトに使用します。

Game.prototype.clicks = function() {
    // Keep a reference to the Game in the scope
    var self = this;

    $('.flip').click(function() {
        if(cardsPlayed.length < 2) //minder dan 2 kaarten gespeeld
        {
            // Use this to refer to the clicked element
            $(this).find('.card').addClass('flipped');
            // Stuff goes here...
            // Use self to refer to the Game object
            self.build();
        }
    }); // Note: no bind, we let jQuery bind this to the clicked element
};
于 2013-01-26T11:10:59.490 に答える
1

私はあなたがこのようなものが欲しいと思います:

function class(){
    var self = this;
    this.build = function(){};
    $('#element').click(function(){
        self.build();
    });
};
于 2013-01-26T09:40:53.727 に答える