这看起来很巧妙,可以“内置”到 jQuery 中,但我认为它仍然值得一问。
我有一个问题,可以通过遍历元素的所有子元素轻松解决。我最近发现我需要考虑比我目前正在做的“1 级”(只需调用 .children() 一次)更深一两级的情况。
jQuery.each(divToLookAt.children(), function(index, element)
{
//do stuff
}
);
这就是我目前正在做的事情。为了深入第二层,我在为每个元素执行填充代码后运行另一个循环。
jQuery.each(divToLookAt.children(), function(index, element)
{
//do stuff
jQuery.each(jQuery(element).children(), function(indexLevelTwo, elementLevelTwo)
{
//do stuff
}
);
}
);
如果我想更深入,我必须重新做一遍。
这显然不好。我很想声明一个“级别”变量,然后将其全部处理。有人对干净高效的 jQueryish 解决方案有任何想法吗?
谢谢!
最佳答案
这是一个很棒的问题,因为关卡很深。 Check out the fiddle .
将其转换为插件。
激活
$('#div').goDeep(3, function(deep){ // $.fn.goDeep(levels, callback)
// do stuff on `this`
});
插件
$.fn.goDeep = function(levels, func){
var iterateChildren = function(current, levelsDeep){
func.call(current, levelsDeep);
if(levelsDeep > 0)
$.each(current.children(), function(index, element){
iterateChildren($(element), levelsDeep-1);
});
};
return this.each(function(){
iterateChildren($(this), levels);
});
};
关于javascript - 遍历 N 级 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4718559/