1

SOLUTION

$(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;
                    }
                }
        });

Thank you for your help guys!

PROBLEM

I am a beginner at JavaScript and jQuery, so I hope some kind soul can help me out. Below is a snippet of a code that executes just fine... but as it is pretty repetitive, I am trying to come up with some code to help me 'automate' all these conditions within the switch statement instead of manually specifying it (if that makes sense). I'm going with a 'for' loop but no results as of yet.

A nudge in the right direction, please? Thank you :)

~ preliminary code ~

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

~ the code it's all about ~

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

        });
4

2 に答える 2

4

Yours is a remarkable approach! I had never considered switch(true) :)

You could try this and see if it works for you:

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");
    }
}
于 2012-07-07T16:05:19.907 に答える
3

As it's only the array index that differs in the different cases:

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;
  }
于 2012-07-07T16:06:29.323 に答える