2

私は jQuery 初心者で、非常に基本的な質問をしようとしているのかもしれませんが、jQuery チェーンが私の場合に機能しない理由を理解するのに本当に苦労しています。

var container = $('#container'),
items = container.find('ul.items'),
moreItems = items.children('li.moreItems');

var config = {
container : container,
items : items,
moreItems : moreItems
}

var app = myApp(config);

function MyApp(config) {
this.container = config.container;
this.items = config.items;
this.moreItems = config.moreItems;
this.current = 0;
}

MyApp.prototype.myUsefulFunction() {
this.moreItems[this.current].fadeIn();
}

それぞれ複数の li を持つ ul 要素で満たされた div#container があるとします。n 番目の li にアクセスして要素をフェードインしたいのですが、コンソールからエラーが返され、fadeIn にはそのようなメソッドがないことが示されます。整理するのを手伝ってくれませんか?

4

3 に答える 3

5

jQuery は、DOMELements を含む一種の配列である jquery オブジェクトを返します。

あなたがそうするとき:this.moreItems[this.current]あなたは実際にjquery配列からDOMElementを抽出します->それをjqueryオブジェクトに変換して、fadeIn()を呼び出せるようにする必要があります!

$(this.moreItems[this.current]).fadeIn();

.eq(index)を使用して、一致したセットをフィルタリングして、インデックスに対応する唯一の要素にすることもできます。

this.moreItems.eq(this.current).fadeIn();

デモ


それとは別に、質問で示したコードにはいくつかの構文エラーがあります。

  1. 関数をプロトタイプに追加するには、次のようにする必要があります。

    MyApp.prototype.myUsefulFunction = function() {}
    

    そしてそうではないMyApp.prototype.myUsefulFunction() {}

  2. new演算子を使用して、の新しいインスタンスを返しますMyApp

    var app = new MyApp(config); // also spelling mistake: myApp != MyApp !!
    
于 2012-03-10T15:02:25.337 に答える
1

チェーン用の jQuery メソッドを作成するには、jQuery.fn を拡張する必要があります

$.fn.myUsefulFunction=function() {
    return this.each(function(){
        $(this).fadeIn();

    })
}

これで、他の jQuery メソッドと同じように使用できます

   $(selector).myUsefulFunction()
于 2012-03-10T15:10:40.227 に答える
0

オフトピック:

  1. クラスのインスタンスを作成するには、 newを使用する必要があります:

    var app = 新しい myApp(config);

  2. myAppMyAppは異なる変数です。

于 2012-03-10T15:08:28.633 に答える