簡體   English   中英

JavaScript的奇怪行為

[英]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();

jsFiddle演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM