0

私は自分のコードをより良く構造化することを学ぼうとしており、いくつかのチュートリアルに従った後、以下のパターンを使い始めました。

この方法で多くの一般的なUIウィジェットを構築することにかなりの成功を収めましたが、最初の壁にぶつかりましたが、以下の.each()ループは実際には各アイテムをループしているようには見えませんが、必要なものを適用しています1回の反復ですべてのアイテムに作用しているかのように動作します。

$ .eachとオブジェクトについて何かを読みましたが、$。eachについてはわかりませんが、それが進むべき方向であるかどうかさえわかりません。

jQuery(document).ready(function($) {

var tabs = {

    trig : $('nav.tab-triggers'),
    content : $('section.tabs-content'),

    init : function() {
        tabs.address([tabs.trig]);
        tabs.address([tabs.content]);
    },

    address : function(item) {
        //for every instance of the item

        $(item).each(function() {
            var i = 1;
            $(this).addClass('tabs-' + i);

            // for ever child element in this instance of the item
            $(this).children().each(function() {
                var count = 1;
                if ( $(this).parent().is('nav') ) {
                    $(this).attr('href', '#tab-' + count);
               } else {
                    $(this).attr('id', 'tab-' + count);
               }

                count++;

            });

            i++;
        });
    },

    display : function () {
        //show hide stuff here.
    }


}

tabs.init();

});
4

1 に答える 1

0

それで、多くの試行錯誤の後で、私はついにそれを機能させました。

基本的に、私が理解しているように、ネストされたオブジェクトを反復処理しようとしているため、.eachを$.eachメソッドに置き換える必要があります。これは少し異なる動作をします。

    address : function(obj) {
        // for each obj
        $.each(obj, function(index,value) {
            //for each instance of the trigger / content item in the obj
             $.each(obj[index], function(index2,value2) {
                //add an incrementing class for each matched element
                $(value2).addClass('tabs-' + index2);
                // get the children of each matched element
                var kids = $(value2).children();
                // loop through each of the children
                $.each(kids, function(index3, value3) {
                    // if its parent is a nav element
                    if ( $(value3).parent().is('nav') ) {
                        // add href
                        $(value3).attr('href', '#tab-' + index3);
                    } else {
                        // add matching ids
                        $(value3).attr('id', 'tab-' + index3);
                    }


                });  // end loop through children elements
             }); // end loop through parent elements
        }); // iteration of passed obj
    }, // end address method

それが新しい方法です-それはうまくいきます。これを行うためのより良い方法はありますか?

于 2013-01-16T07:38:46.990 に答える