Cycle through multiple background colors - Seeking code improvement

前端 未结 2 904
慢半拍i
慢半拍i 2020-12-20 06:36

Check out my fiddle here

Here is the js in question:

 $(document).ready(function() {
    $(\'.clickMe\').toggle(
        function() {
            $(\         


        
相关标签:
2条回答
  • 2020-12-20 06:57

    DRYing it a bit:

      var counter = 0;
      var colors = [
        "#eeeeee",
        "#00ff00",
        "#ff0000",
        "#000000"      
      ];
    
      var $div = $('#coloredDiv');
    
      $('.clickMe').click(function(){
    
        $div.css({
            "background-color": colors[(counter++)%colors.length]
        })
    
      });
    

    With the modulo operator [%], you loop over the array without exceeding its bounds [a%bevaluates to b-1 at most].

    EDIT: you just increment the counter, then the modulo will "reset" it to 0 every array.length iterations [it won't be reset actually, just the result of the expression will look like]. Search wikipedia for modulo operator, you will find out a lot of interesting properties.

      i | (i++)%arr.length
    ---------
    | 0 | 0 |
    | 1 | 1 |
    | 2 | 2 |
    | 3 | 3 |
    | 4 | 0 |
    | 5 | 1 |
    | 6 | 2 |
    | 7 | 3 |
       ...
    
    0 讨论(0)
  • 2020-12-20 07:10

    Don't know better or not but have a look at the following:

    <div id="coloredDiv" data-index="-1"></div>
    

    Note the data attribute added to div.

    var colors = ['#eeeeee', "#00ff00", "#ff0000", "#000000"];
    
    $(document).ready(function () {
        $colorDiv = $('#coloredDiv');
        ln = colors.length;
        $('.clickMe').on("click", function () {
            var i = $colorDiv.data("index");
            ++i;
            if (i >= ln) i = 0;
            $colorDiv.css({
                'background-color': colors[i]
            });
            $colorDiv.data("index", i);
        });
    });
    

    Working fiddle is here.

    0 讨论(0)
提交回复
热议问题