2012-07-07 60 views
1

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; 
      } 

     }); 
+0

这是错误的:'i> offset.length'它应该是'我 3',这是错误的。 – 2012-07-07 16:18:51

回答

3

因为它只是在不同的情况不同的数组索引:

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; 
    } 
+0

为什么使用名称'i'而不是'index'? “i”是有史以来最差的变量名,看起来很像'1','l'和'i'。 – Hogan 2012-07-07 16:08:34

+0

我只是好奇:OP的答案是否会导致跳转到评估为真的第一条语句?我想象的JavaScript内部工作原因导致每一个被检查,直到发现一个真正的 – abelito 2012-07-07 16:10:11

+0

感谢您的快速回复!我以前尝试过(尽管我认为你的意思是“i> offset.length”)。它不起作用!嗯。 – AKG 2012-07-07 16:13:50

4

你是一个了不起的方法!我从来没有考虑switch(true) :)

你可以试试这个,看看它是否适合你:

for (var i = 0; i<=2; i++) 
{ 
    if (y < offset[i].bottom) { 
     $("#catSelect option:selected").removeAttr("selected"); 
     $("#catSelect option[value=#"+offset[i].id+"]").attr("selected", "selected"); 
    } 
} 
+1

为什么使用名称'i'而不是'index'? “i”是有史以来最差的变量名,看起来很像'1','l'和'i'。 – Hogan 2012-07-07 16:09:15