Cycle through multiple background colors - Seeking code improvement

前端 未结 2 906
慢半拍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 |
       ...
    

提交回复
热议问题