我正在用Javascript / jQuery创建一个带有我自己的定制步骤的滑块。
这里我使用的是一个for循环,但是我的函数只起作用,当我将一个while循环放入其中时。
work) First代码(没有while )
var steps = '';
// Setting up the steps according to the number of slides
for( var i = 0; i < $itemsCount; ++i ) {
var step = '';
// Find step number and step text
var step_text = $items.eq(i).attr('data-title');
var step_count = i + 1;
// current step will have the class 'current'
var step = i === current ? '<li class="step current"><span data-step="'+ step_count +'">'+ step_text +'</span></li>' : '<li class="step"><span data-step="'+ step_count +'">'+ step_text +'</span></li>';
i++;
steps += step;
}
var navSteps = $( '<ul class="steps"/>' ).append(steps).prependTo($slider);第二代码 (Did - with while )
var steps = '';
// Setting up the steps according to the number of slides
for( var i = 0; i < $itemsCount; ++i ) {
var step = '';
// Find step number and step text
while (i < $itemsCount) {
var step_text = $items.eq(i).attr('data-title');
var step_count = i + 1;
// current step will have the class 'current'
var step = i === current ? '<li class="step current"><span data-step="'+ step_count +'">'+ step_text +'</span></li>' : '<li class="step"><span data-step="'+ step_count +'">'+ step_text +'</span></li>';
i++;
steps += step;
}
}
var navSteps = $( '<ul class="steps"/>' ).append(steps).prependTo($slider);这并不是一个真正的问题,但我仍然不知道为什么第一个没有工作。
有人能告诉我为什么我要用while代替循环吗?
发布于 2014-05-01 16:14:39
在第一个例子中,您要增加两次"i“:一次在循环主体的末尾,一次在循环头中(圆括号中的i++ )。
添加while循环时,基本上会使for循环(大部分)变得无关紧要,因为当while循环退出时,"i“的值也会导致for循环退出。
https://stackoverflow.com/questions/23411665
复制相似问题