2

bind を使用して「this」のスコープを変更しているため、クリック関数内から「this」を使用して generateContent 関数を参照できます。残念ながら、これは「this」のスコープが変更されたため、this.id が機能しなくなったことを意味します。

この場合、クリックされたボタンのIDを取得する最良の方法は何ですか:

function help( doc ) {

    buttons: function() {

        $('.add-btn').click( function() {

        this.generateContent( this.id ) );

        }.bind(this));

    },

    generateContent: function ( id ){

    }

}

// This function binds a function to an object's scope.
Function.prototype.bind = function(scope) {
    var _function = this;
    return function() {
        return _function.apply(scope, arguments);
    }
}
4

1 に答える 1

5

あなたはjQueryにタグを付けませんでしたが、あなたのコードはjQueryのように鳴るので、jQueryを想定しています。

jQuery は以下を提供しますevent.currentTarget

$('.add-btn').click( function(e) {
     this.generateContent( e.currentTarget.id ) ;
}.bind(this));

ところでFunction.prototype.bind、ネイティブに存在しますが、ネイティブ バージョンが利用可能な場合に上書きする必要はありません。jQuery も を提供し$.proxyているため、いずれの場合も必要ありません。

デモを見る

于 2012-07-23T14:09:53.003 に答える