0

次のように単純な jquery プラグインを作成しました。

$.fn.greenify = function () {
    var color = "green";
    this.css("color", color);

    function getColor() {
        return "green";
    }
};

//calling plugin
$("#test").greenify();

関数 getColor() を呼び出すためにこれを行いたいこと。以下に示すようなもの:

var v1 = $("#test").greenify();
var color = v1.getColor();    

これは確かにそれを行う方法ではありません。どうすればそのような電話をかけることができますか?

4

3 に答える 3

2

関数を含むオブジェクトを返す必要があります。

return { getColor: someFunction };
于 2013-06-13T12:34:57.933 に答える
2

@MattBallの回答に基づいて、プラグインコンテキスト内で渡されたjQueryオブジェクトを拡張することにより、連鎖性を維持できます。

$.fn.greenify = function () {
    var color = 'green';
    this.getColor = function () {
        return 'green';
    };
    return this;
};

// so this will work:
$('#test').greenify().addClass('used-jquery-method');

// but you won't be able to do it again if you select again:
var color = $('#test').getColor();  // unknown method

// you'll have to cache it instead, and build from the same 'chain'
var element = $('#test').greenify().addClass('used-jquery-method');
var color = element.getColor();
于 2013-06-13T12:46:10.153 に答える
1

連鎖性を壊すのは慣用的な jQuery ではありませんが、これは機能します。

$.fn.greenify = function() {
   var color="green";
   this.css( "color", color );

   return {
       getColor: function () {
           return "green";
       }
   };
};
于 2013-06-13T12:35:09.717 に答える