[英]JavaScript's strange behavior
如果取消注釋body.children().each(calc_deep(1));
然后我得到TypeError: Object [object Window] has no method 'attr'
在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();
each
函數都使用一個函數作為參數,因此您要傳遞undefined
的參數-因為先調用該函數,然后函數的返回值才是each()
得到的值。
請改用function() {calc_deep(1);}
。
deepest
是變量body
,它是一個jQuery對象。 稍后,當您為this
分配最深時,它是一個常規DOM元素,沒有attr
函數。
您有一個更大的問題- 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.