【发布时间】:2012-07-07 16:01:12
【问题描述】:
解决方案
$(window).scroll(function() {
var y = $(this).scrollTop();
for (var i = 0; i < offset.length; i++)
{
if (y < offset[i].bottom) {
$("#catSelect option:selected").removeAttr("selected");
$("#catSelect option[value=#"+offset[i].id+"]").attr("selected", "selected");
break;
}
}
});
感谢你们的帮助!
问题
我是 JavaScript 和 jQuery 的初学者,所以我希望有好心人可以帮助我。 下面是一个执行得很好的代码的 sn-p ......但由于它非常重复,我试图想出一些代码来帮助我在 switch 语句中“自动化”所有这些条件,而不是手动指定它(如果这有意义的话)。我将使用“for”循环,但目前还没有结果。
请向正确的方向轻推,好吗?谢谢你:)
~初步代码~
var offset = [];
$(".cat").each(function() {
var top = $(this).offset().top;
var bottom = top + $(this).outerHeight();
var id = $(this).attr("id");
offset.push({"top": top, "bottom": bottom, "id": id });
$(document.body).append(offset.length);
});
~就是代码~
$(window).scroll(function() {
var y = $(this).scrollTop();
switch (true) {
case (y < offset[0].bottom):
$("#catSelect option:selected").removeAttr("selected");
$("#catSelect option[value=#"+offset[0].id+"]").attr("selected", "selected");
break;
case (y < offset[1].bottom):
$("#catSelect option:selected").removeAttr("selected");
$("#catSelect option[value=#"+offset[1].id+"]").attr("selected", "selected");
break;
case (y < offset[2].bottom):
$("#catSelect option:selected").removeAttr("selected");
$("#catSelect option[value=#"+offset[2].id+"]").attr("selected", "selected");
break;
}
});
【问题讨论】:
-
这是错误的:
i > offset.length应该是i < offset.length,所以它的计算结果是0 < 3,1 < 3,2 < 3,停止。您的循环永远不会运行,因为第一个评估是0 > 3,这是错误的。
标签: javascript jquery loops scroll switch-statement