2

次のことができるある種の構造を作成することが可能かどうか疑問に思います:

$("some element").somemethod(arg)、これは言うこととまったく同じです$.somemethod("some element", arg)

たとえば、$(selector).each(callback)jquery で使用できることはわかっています。これは、$.each(selector, callback). ただし、jquery がこれを行う方法を理解するのは難しいと思います。メソッド「each」が2回定義されているようですが、これは避けたいものです。これは可能ですか?

4

3 に答える 3

5

これらは 2 回定義されていますが、実際に作業を行うコードは 1 回しか書かれていません。

$.myPlugin = function(element,text){
    $(element).text(text); // work is done here
    return element;
}
$.fn.myPlugin(function(text) {
    return $.myPlugin(this,text);
});

これが jQuery のコア内で使用されている例を次に示します。

https://github.com/jquery/jquery/blob/1.9-stable/src/core.js#L250

于 2013-05-16T15:13:33.320 に答える
3

はい、可能です。そのためには独自のプラグインを実装する必要があります。

(function( $ ) {
    $.fn.somemethod = function() {
        return this.each(function() {
            // do something to each element here
        });
    };
}( jQuery ));
于 2013-05-16T15:11:50.083 に答える
0

次のような意味ですか。


function $(context){
    this.context = context;
    if(!(this instanceof $)) return new $(context);
}

$.prototype.somemethod = function(arg){
    // The bulk of the function is defined here, only once
    console.log("Doing some stuff to " + this.context + " with " + arg);
}

$.somemethod = function(context, arg){
    $(context).somemethod(arg);
}

$('body').somemethod(7); // Doing some stuff to body with 7
$.somemethod('body', 7); // Doing some stuff to body with 7
于 2013-05-16T15:10:52.593 に答える