问问题
1006 次
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. */
更新:
我想我误解了原来的问题。如果您使用.expandNav
该类来标记用于显示/隐藏更详细信息的链接(如果您愿意,可以使用可展开的树视图),并且您只希望<ul>
s 之前的链接获取该类,那么您实际上想要更像这样的东西:
$('#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 回答