SOLUTIONJavaScript/jQuery:可能通过for循环“自动化”switch语句?
$(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的初学者,所以我希望某种灵魂可以帮助我。 下面是一段执行得很好的代码片段,但由于它很重复,我试图想出一些代码来帮助我在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'它应该是'我 3',这是错误的。 –
2012-07-07 16:18:51