【问题标题】:javascript nested loop variable scope issuejavascript嵌套循环变量范围问题
【发布时间】:2012-11-29 15:08:03
【问题描述】:

我正在编写一个受https://stackoverflow.com/a/3834694/721084 启发的简单面包屑。我试图通过它所在的页面对每个项目进行分类来实现这一点。下面的代码旨在做到这一点,但它总是以无限循环结束。我做错了什么?

编辑:Pastebin 链接到整个 JS 代码 http://pastebin.com/nxUhQmqF

示例 DOM:

<ul id="progress_bar" class="nostyle clearfix">
    <li class="first"><a href="">Blah</a></li>
    <li class=""><a href="">Blah</a></li>
    <li class="selected"><a href="">Blah</a></li>
    <li class="last"><a href="">Blah</a></li>
</ul>

JS代码:

    function classifyPages(bcParent, totalItems) {
    var pages       = 1,
        wd          = 0,
        parentWd    = findWidthOfParent(bcParent),
        crumbs      = bcParent.find('li'),
        i           = 0;

    for( i = 0; i < totalItems; i++) {
        wd = 0;
        while(wd < parentWd) {
            crumb = crumbs.eq(i);
            wd += crumb.outerWidth();
            if( wd < parentWd) {
                i += 1;
                crumb.addClass( 'bcPage-' + pages);
            }
        }

        pages += 1;
    }

    return pages;
}

【问题讨论】:

  • 您能否向我们展示一个(最小)示例 DOM 以及如何调用该函数?另外,findWidthOfParent 返回什么?
  • 你能给我们看一些 html,以及你是如何调用这个函数的吗?
  • 您确定 crumb.outerWidth 返回一个有效数字吗?如果没有,它可以进入无限循环。
  • @Bergi:用链接和 DOM 更新了我的问题

标签: javascript jquery breadcrumbs


【解决方案1】:

您的i 也在内部循环中递增,有时会在totalItems 之上运行。不存在的crumb 总是有0outerWidth,你就被抓住了(正如@Oleg V. Volkov 所描述的那样)。

这应该可行:

function classifyPages(bcParent, totalItems) {
    var pages       = 1,
        parentWd    = findWidthOfParent(bcParent),
        crumbs      = bcParent.find('li');

    for (var i = 0; i < totalItems; i++) {
        for (var wd = 0; wd < parentWd && i < totalItems; ) {
//                                     ^^^^^^^^^^^^^^^^^
            var crumb = crumbs.eq(i);
            wd += crumb.outerWidth();
            if( wd < parentWd) {
                i += 1;
                crumb.addClass( 'bcPage-' + pages);
            }
        }
        pages += 1;
    }
    return pages;
}

更好:

function classifyPages(bcParent, totalItems) {
    var pages       = 1,
        parentWd    = findWidthOfParent(bcParent),
        crumbs      = bcParent.find('li'),
        wd          = 0;

    for (var i = 0; i < totalItems; i++) {
        var crumb = crumbs.eq(i);
        wd += crumb.outerWidth();
        if( wd >= parentWd) {
            pages += 1;
            wd = 0; // reset
        }
        crumb.addClass( 'bcPage-' + pages);
    }
    return pages;
}

【讨论】:

    【解决方案2】:

    我怀疑这个 while 循环 - 这种结构经常恰好是无限循环的来源:

     while(wd < parentWd) {
                crumb = crumbs.eq(i);
                wd += crumb.outerWidth();
                // snip
    

    如果crumb.outerWidth() 始终返回 0,它将永远不会结束。

    【讨论】:

      猜你喜欢
      • 2011-09-16
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多