首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript的奇怪行为

JavaScript的奇怪行为
EN

Stack Overflow用户
提问于 2012-07-26 06:52:08
回答 2查看 71关注 0票数 0

如果取消注释body.children().each(calc_deep(1));,那么我会在parseInt(deepest.attr('deep'))字符串上得到TypeError: Object [object Window] has no method 'attr',但是如果没有取消注释,你可以在控制台中检查你可以调用deepest.attr('deep')。那是什么?

代码语言:javascript
复制
    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();
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-26 07:04:09

第一个deepest是变量body,它是一个jQuery对象。稍后,当您将deepest赋值给this时,它是一个没有attr函数的常规DOM元素。

您有一个更大的问题- this没有指向您认为的元素。调用不带函数参数的$(this).children().each(calc_deep);。要获得深度,只需从父级获取。您正在调用函数calc_deep并将(不存在的)返回值传递给each。您希望将函数本身传递给每个。

代码语言:javascript
复制
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

票数 1
EN

Stack Overflow用户

发布于 2012-07-26 06:55:07

each接受一个函数作为参数,你传递给它的是undefined -因为你首先调用函数,然后它的返回值就是each()得到的。

请改用function() {calc_deep(1);}

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11659851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档