Javascript 中断的JQuery循环

Javascript 中断的JQuery循环,javascript,jquery,Javascript,Jquery,我的选项卡是使用PHP创建的,所以我不希望每个tabswitcher选项卡设置宽度。由于这个原因,我试图将tabswitcher的总宽度相加,这样我就可以设置宽度,然后应用边距:0 auto 警告var width正在返回NaN。这是我第一次尝试循环,可能在什么地方搞砸了!(显然……) JQuery var width; var NumOfTabs = $('.TabSwitcher .Tab').length; var count = 1; while (count < NumOfTab

我的选项卡是使用PHP创建的,所以我不希望每个tabswitcher选项卡设置宽度。由于这个原因,我试图将tabswitcher的总宽度相加,这样我就可以设置宽度,然后应用
边距:0 auto

警告
var width
正在返回NaN。这是我第一次尝试循环,可能在什么地方搞砸了!(显然……)

JQuery

var width;
var NumOfTabs = $('.TabSwitcher .Tab').length;
var count = 1;
while (count < NumOfTabs){
    width = width + $('.TabSwitcher .Tab:nth-child(' + count + ')').width();
    count++;
}
width = width + (NumOfTabs * 4) // Add passing
$('.TabSwitcher').css({'width': width + 'px'});
var宽度;
var NumOfTabs=$('.TabSwitcher.Tab').length;
var计数=1;
while(计数
HTML

<div class="TabSwitcher">
    <div class="Tab Active" id="Page_1">1</div>
    <div class="Tab" id="Page_2">2</div>
</div>

1.
2.

我认为你应该考虑使用jQuery的Hoyy <代码>每个方法,类似于:

var width = 0;
var tabs = $('.TabSwitcher .Tab');
tabs.each(function(index, tab) {
    width += $(tab).width();
});
width += (tabs.length * 4); // Add padding
$('.TabSwitcher').css({'width': width + 'px'});

您还应该注意,
width
必须实例化为
0
。否则,添加到它只会产生
NaN

不要继续查找。所有这一切将使它缓慢,因为你一直在寻找同一件事,一遍又一遍

var width = 0;  //you original issue, initialize it with a start value
var tabs = $('.TabSwitcher .Tab'); //store it do not look it up over and over
var numOfTabs = tabs.length;

tabs.each( function() {  //use each to loop
    width = width + $(this).width();  //"this" is the current tab
});

width = width + (numOfTabs * 4) // Add padding
$('.TabSwitcher').css({'width': width + 'px'});


在这里,您可以使用每个来查找所有宽度并将它们添加到一起

我没有看到任何
var保证金
,而是
var宽度
吗?
width
最初是
NULL
。很难添加
NULL
@toma现在它不是NULL,它是未定义的。你会为未定义的/NULL和其他事情争论吗?试着回答。@AdrianIftode我看这里没有争论。我甚至看到了一个答案,两次。谢谢你的回答:)顺便说一句,虽然这是一个很好的建议,但隐藏在你的答案中的事实是OP唯一的缺陷是他们没有初始化
width
0@Regent谢谢我略读了一下,但使用
+=
更好。我已经更新了我的答案。
var width = 0;

$('.TabSwitcher .Tab').each(
function(index, el) {
   width = width + $(el).width();
}
);

$('.answer').html(width);