1
4

2 に答える 2

1

再帰的 (= 自分自身を呼び出す) 関数でそれを行うことができます:

/* 
    Recursive loop though UL list
*/

function loopDown($obj, x){

    // Store our current jquery objects
    var $sub = $obj.children('ul').children('li:has(ul)');
    var $a = $sub.children('a');

    // Test is we need to continue loop - if not the function ends itself.
    if ($sub){

        if (x !== 0) {
            $a.addClass('expandNav'+x);
        }

        else {
            $a.addClass('expandNav');
        }

        //Incriment counter
        x++;

        $sub.each(function(){
            // Call the function one down the line...
            loopDown($(this), x);           
        });         
    }       
}

// Run our function, pass it the jQuery object and a starting counter.
loopDown($('#ContentLeftNav'), 0);  
于 2011-02-22T00:13:38.103 に答える
1

各リンク.parents()で関連付けられた関数を使用できます。.length

$('#ContentLeftNav a').each(function() {
    $(this).addClass('expandNav' + $(this).parents('#ContentLeftNav ul').length);
});

ただし、これをスタイリングに使用するだけの場合は、プレーンな CSS を使用し、JS を完全にスキップすることを検討することをお勧めします。

#ContentLeftNav ul a {...}
#ContentLeftNav ul ul a {...}
#ContentLeftNav ul ul ul a {...}
/* And so forth. */

アップデート:

元の質問を誤解していたと思います。クラスを使用して、より詳細な情報を表示/非表示にするために使用されるリンクをマークし (必要に応じて展開可能なツリー ビュー)、クラスを取得するために s の.expandNav直前のリンクのみが必要な場合は、実際には<ul>このようなもの:

$('#ContentLeftNav a + ul').each(function() {
    // $(this) is the ul, so $(this).prev() is the a:
    $(this).prev().addClass('expandNav' + $(this).parents('#ContentLeftNav ul').length);
});

お役に立てれば!

于 2011-02-21T21:52:17.443 に答える