如果取消注释body.children().each(calc_deep(1));,那么我会在parseInt(deepest.attr('deep'))字符串上得到TypeError: Object [object Window] has no method 'attr',但是如果没有取消注释,你可以在控制台中检查你可以调用deepest.attr('deep')。那是什么?
var deepest;
var calc_deep = function(i)
{
$(this).attr('deep',i);
if(i>parseInt(deepest.attr('deep')))
deepest=this;
$(this).children().each(calc_deep(i+1));
}
var find_deepest = function()
{
body=$('body').children().eq(0);
body.attr('deep',0);
deepest=body;
//body.children().each(calc_deep(1));
}
find_deepest();发布于 2012-07-26 07:04:09
第一个deepest是变量body,它是一个jQuery对象。稍后,当您将deepest赋值给this时,它是一个没有attr函数的常规DOM元素。
您有一个更大的问题- this没有指向您认为的元素。调用不带函数参数的$(this).children().each(calc_deep);。要获得深度,只需从父级获取。您正在调用函数calc_deep并将(不存在的)返回值传递给each。您希望将函数本身传递给每个。
var deepest, index;
var calc_deep = function() {
var $this = $(this); //cache jQuery this
var i = $this.parent().data("deep") + 1;
$this.data('deep', i);
if (i > index) {
deepest = $this;
index = i;
}
$this.children().each(calc_deep);
}
var find_deepest = function() {
body = $('body').children().eq(0);
body.data('deep', 0);
index = 0;
deepest = body;
body.children().each(calc_deep);
}
find_deepest();jsFiddle demo
发布于 2012-07-26 06:55:07
each接受一个函数作为参数,你传递给它的是undefined -因为你首先调用函数,然后它的返回值就是each()得到的。
请改用function() {calc_deep(1);}。
https://stackoverflow.com/questions/11659851
复制相似问题