gpt4 book ai didi

javascript嵌套循环变量作用域问题

转载 作者:行者123 更新时间:2023-12-02 19:11:49 28 4
gpt4 key购买 nike

我正在写一个简单的面包屑,灵感来自 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;
}

最佳答案

您的i(也在内部循环中递增)有时会在totalItems之上运行。然后,不存在的 crumbouterWidth 始终为 0,您就会被捕获(如@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;
}

关于javascript嵌套循环变量作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13628702/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com