如果/ else语句似乎很长,寻找简化代码的方法

时间:2015-07-03 19:20:31

标签: javascript jquery

查看我的代码,包含if / else语句的部分在scripts.js中完全符合我的要求,但它并不是解决问题的最有效方法。

问题

我有一个小导航(左侧),显示七个宠物名称。被收养的宠物总数是四十。当用户向下滚动页面时,导航中包含宠物名称的HTML和链接会在每七只宠物之后发生变化。

JSFiddle:http://jsfiddle.net/8cnq58x4/1/

(You may have to expand the "Result" window to see the small navigation)

scripts.js中

$(function(){
      /*-------------------------------------
      TABLETOP.JS
      --------------------------------------*/
      var public_spreadsheet_url = "https://docs.google.com/spreadsheets/d/1TOIGfwdi1GhV7BMhc5fH481icHi7zEEyXZZx3Y5J61I/pubhtml";

      $(document).ready( function() {
        Tabletop.init( { key: public_spreadsheet_url,
            callback: showInfo,
            parseNumbers: true } );
      });
      function showInfo(data, tabletop) {
        var source   = $("#pets").html();
        var template = Handlebars.compile(source);

        // The actual name of the sheet, not entire .csv
        $.each(tabletop.sheets("Pets").all(), function(i, fact) {
            var html = template(fact);

          // You need an element with this id or class in your HTML
          $("#pets-list").append(html);
          $('.container').eq(i).addClass(data.Pets.elements[i]);
          // console.log(data.Pets.elements[i].name);

            // Deals with the left menu
            $(".nameNav").click(function(){
               $(".nameNav").removeClass("active");
               $(this).toggleClass("active");
            });

            /* -------------------------------------
            NAVIGATION
            --------------------------------------*/

            $(window).scroll(function(){
                var $pets = $('.pet').map(function(_, i){
                    return $(i).offset().top;
                });

                var scroll = $(window).scrollTop();
                  var index = $pets.filter(function(i, v){ if(v < scroll) return i; }).length;
                  $(".nameNav").removeClass("active");
                  $(".nameNav").eq(index).addClass("active");

                  var navElements = $(".nameNav"); navElements.eq(index % navElements.length).addClass("active");

                  if (index >= 7 && index <= 13) {
                     $(".first").html(data.Pets.elements[7].name);
                     $("#pet-one").attr("href", "#" + data.Pets.elements[7].name);

                     $(".second").html(data.Pets.elements[8].name);
                     $("#pet-two").attr("href", "#" + data.Pets.elements[8].name);

                     $(".third").html(data.Pets.elements[9].name);
                     $("#pet-three").attr("href", "#" + data.Pets.elements[9].name);

                     $(".fourth").html(data.Pets.elements[10].name);
                     $("#pet-four").attr("href", "#" + data.Pets.elements[10].name);

                     $(".fifth").html(data.Pets.elements[11].name);
                     $("#pet-five").attr("href", "#" + data.Pets.elements[11].name);

                     $(".sixth").html(data.Pets.elements[12].name);
                     $("#pet-six").attr("href", "#" + data.Pets.elements[12].name);

                     $(".seventh").html(data.Pets.elements[13].name);
                     $("#pet-seven").attr("href", "#" + data.Pets.elements[13].name);

                  } else if (index >= 14 && index <= 20) {
                     $(".first").html(data.Pets.elements[14].name);
                     $("#pet-one").attr("href", "#" + data.Pets.elements[14].name);

                     $(".second").html(data.Pets.elements[15].name);
                     $("#pet-two").attr("href", "#" + data.Pets.elements[15].name);

                     $(".third").html(data.Pets.elements[16].name);
                     $("#pet-three").attr("href", "#" + data.Pets.elements[16].name);

                     $(".fourth").html(data.Pets.elements[17].name);
                     $("#pet-four").attr("href", "#" + data.Pets.elements[17].name);

                     $(".fifth").html(data.Pets.elements[18].name);
                     $("#pet-five").attr("href", "#" + data.Pets.elements[18].name);

                     $(".sixth").html(data.Pets.elements[19].name);
                     $("#pet-six").attr("href", "#" + data.Pets.elements[19].name);

                     $(".seventh").html(data.Pets.elements[20].name);
                     $("#pet-seven").attr("href", "#" + data.Pets.elements[20].name);

                  } else if (index >= 21 && index <= 27) {
                    $(".first").html(data.Pets.elements[21].name);
                    $("#pet-one").attr("href", "#" + data.Pets.elements[21].name);

                    $(".second").html(data.Pets.elements[22].name);
                    $("#pet-two").attr("href", "#" + data.Pets.elements[22].name);

                    $(".third").html(data.Pets.elements[23].name);
                    $("#pet-three").attr("href", "#" + data.Pets.elements[23].name);

                    $(".fourth").html(data.Pets.elements[24].name);
                    $("#pet-four").attr("href", "#" + data.Pets.elements[24].name);

                    $(".fifth").html(data.Pets.elements[25].name);
                    $("#pet-five").attr("href", "#" + data.Pets.elements[25].name);

                    $(".sixth").html(data.Pets.elements[26].name);
                    $("#pet-six").attr("href", "#" + data.Pets.elements[26].name);

                    $(".seventh").html(data.Pets.elements[27].name);
                    $("#pet-seven").attr("href", "#" + data.Pets.elements[27].name);

                  } else if (index >= 28 && index <= 34) {
                    $(".first").html(data.Pets.elements[28].name);
                    $("#pet-one").attr("href", "#" + data.Pets.elements[28].name);

                    $(".second").html(data.Pets.elements[29].name);
                    $("#pet-two").attr("href", "#" + data.Pets.elements[29].name);

                    $(".third").html(data.Pets.elements[30].name);
                    $("#pet-three").attr("href", "#" + data.Pets.elements[30].name);

                    $(".fourth").html(data.Pets.elements[31].name);
                    $("#pet-four").attr("href", "#" + data.Pets.elements[31].name);

                    $(".fifth").html(data.Pets.elements[32].name);
                    $("#pet-five").attr("href", "#" + data.Pets.elements[32].name);

                    $(".sixth").html(data.Pets.elements[33].name);
                    $("#pet-six").attr("href", "#" + data.Pets.elements[33].name);

                    $(".seventh").html(data.Pets.elements[34].name);
                    $("#pet-seven").attr("href", "#" + data.Pets.elements[34].name);

                  } else if (index >= 35 && index <= 38) {
                    $(".first").html(data.Pets.elements[35].name);
                    $("#pet-one").attr("href", "#" + data.Pets.elements[35].name);

                    $(".second").html(data.Pets.elements[36].name);
                    $("#pet-two").attr("href", "#" + data.Pets.elements[36].name);

                    $(".third").html(data.Pets.elements[37].name);
                    $("#pet-three").attr("href", "#" + data.Pets.elements[37].name);

                    $(".fourth").html(data.Pets.elements[38].name);
                    $("#pet-four").attr("href", "#" + data.Pets.elements[38].name);
                  } else {
                    $(".first").html(data.Pets.elements[0].name);
                    $("#pet-one").attr("href", "#" + data.Pets.elements[0].name);

                    $(".second").html(data.Pets.elements[1].name);
                    $("#pet-two").attr("href", "#" + data.Pets.elements[1].name);

                    $(".third").html(data.Pets.elements[2].name);
                    $("#pet-three").attr("href", "#" + data.Pets.elements[2].name);

                    $(".fourth").html(data.Pets.elements[3].name);
                    $("#pet-four").attr("href", "#" + data.Pets.elements[3].name);

                    $(".fifth").html(data.Pets.elements[4].name);
                    $("#pet-five").attr("href", "#" + data.Pets.elements[4].name);

                    $(".sixth").html(data.Pets.elements[5].name);
                    $("#pet-six").attr("href", "#" + data.Pets.elements[5].name);

                    $(".seventh").html(data.Pets.elements[6].name);
                    $("#pet-seven").attr("href", "#" + data.Pets.elements[6].name);
                  }

                  /* -------------------------------------
                  HIDE SOME PETS
                  --------------------------------------*/

                  if (index >= 35 && index <= 38) {
                    $(".fifth").addClass("hide");
                    $(".sixth").addClass("hide");
                    $(".seventh").addClass("hide");
                  } else {
                    $(".fifth").removeClass("hide");
                    $(".sixth").removeClass("hide");
                    $(".seventh").removeClass("hide");
                  }
      });
    });
    };
});

的index.html

<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
    <meta charset="UTF-8">
    <title>Name of Website</title>
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="assets/css/style.css">
    <link href='http://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
    <!-- <link rel="icon" type="image/png" href="assets/img/favicon.ico"> -->
</head>
<body>
    <nav class="vertical">
        <div class="rectangle">
            <a href="#Adonis" id="pet-one"><p class="nameNav first active">Adonis</p></a>
            <a href="#Billy" id="pet-two"><p class="nameNav second">Billy</p></a>
            <a href="#Comet" id="pet-three"><p class="nameNav third">Comet</p></a>
            <a href="#Dexter" id="pet-four"><p class="nameNav fourth">Dexter</p></a>
            <a href="#Evan" id="pet-five"><p class="nameNav fifth">Evan</p></a>
            <a href="#Fritz" id="pet-six"><p class="nameNav sixth">Fritz</p></a>
            <a href="#Grommit" id="pet-seven"><p class="nameNav seventh">Grommit</p></a>
        </div><!-- /.rectangle -->
    </nav>

    <main>
        <div id="pets-list"></div>
    </main>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
    <script src="assets/js/scripts.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tabletop.js/1.3.5/tabletop.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.0/handlebars.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js"></script>

        <!-- This is where the template for pets goes -->
        <script id="pets" type="text/x-handlebars-template">
            <div class="container">
                <div class="pet">
                    <p class="nameTitle" id="{{name}}">{{name}}</p>
                    <img src="{{image}}" alt="">
                    <p class="breed">{{breed}}</p>
                    <p class="description">{{description}}</p>
                    <p class="cost">{{cost}}</p>
                    <hr>
                </div><!-- /.pet -->
            </div><!-- /.container -->
        </script>
</body>
</html>

3 个答案:

答案 0 :(得分:5)

用以下代码替换整个if / else块:

var places_arr = [".first", ".second", ".third", ".fourth", ".fifth", ".sixth", ".seventh"];
var nbs_arr = ["one", "two", "three", "four", "five", "six", "seven"];
for(var pet_ind = 0; pet_ind < 7; pet_ind++){
    var final_pet_index = index-(index%7)+pet_ind;
    $(places_arr[pet_ind]).html(data.Pets.elemets[final_pet_index].name);
    $("#pet-"+nbs_arr[pet_ind]).attr("href", "#" + data.Pets.elements[final_pet_index].name);                  
}

答案 1 :(得分:0)

如果通过以下方法

,你可以摆脱if else
// Handling of else scenario
var counter = 0;
if(index > 0 && index <= 38) {
    counter = Math.floor(index/7)*7;
}

// elements classes array 
var arr1 = [".first", ".second", ".third", ".fourth", ".fifth", ".sixth", ".seventh"];
var arr2 = ["one", "two", "three", "four", "five", "six", "seven"];

// Iteration
for (var i = 0; i < 7; i++) {
    $(arr1[i]).html(data.Pets.elements[counter+i].name);
    $("#pet-" + arr2[i]).attr("href", "#" + data.Pets.elements[counter+i].name);

    // Handle specific scenario for index 35 to 38.
    if(counter == 35 && i == 3) {
         break;
    }
}

// Additional check for specific scenario for index 35 to 38
if (counter == 35) {
        $(".fifth").addClass("hide");
        $(".sixth").addClass("hide");
        $(".seventh").addClass("hide");
} else {
        $(".fifth").removeClass("hide");
        $(".sixth").removeClass("hide");
        $(".seventh").removeClass("hide");
}

答案 2 :(得分:0)

我认为你可以像comodin一样使用。

你正在使用数字的保证:

1)从7到13 2)从14到20 3)从21到27

依旧......

所以,例如,你可以看看索引是否介于某些限制之间,并做了类似的事情......

if (index >= 7 && index <= 13) {
   comodin=7;
}
if (index >= 14 && index <= 20) {
   comodin=14;
}
...

并且finnaly:

(".first").html(data.Pets.elements[comodin].name);
$("#pet-one").attr("href", "#" + data.Pets.elements[comodin].name);

$(".second").html(data.Pets.elements[comodin+1].name);
$("#pet-two").attr("href", "#" + data.Pets.elements[comodin +1].name);

......等等......