简体   繁体   中英

How can I Use a javascript for loop to create a table with multiple rows?

I want to make a table of colors with eight rows using a javascript for loop. I did this with php and mysql but I can't seem to figure out how to output the and tags to create the distinct rows. So far this is what I have (The table has an id="colorpicker"):

 <script type="text/javascript">

 var colors = ['000033', '000066', '000099', '0000CC', '0000FF', '003300',    '003333', '003366', '003399', '0033CC', '0033FF', '006600', '006633', '006666', '006699', '0066CC'];
 var i = 0;
 var len = colors.length;
 var colorpicker = "";
 var a = colors.indexOf('i');

 for (i = 0; i < len; i++) {

colorpicker += "<tr><td style='color:#"+colors[i]+"'>"+colors[i] +"</td>  </tr>";
}

document.getElementById("colorpicker").innerHTML = colorpicker;

</script>

What I think I need to do is determine the index of the colors and then use modular division to determine whether the index % 8 === 0. This is what I tried that didn't work:

 var colors = ['000033', '000066', '000099', '0000CC', '0000FF', '003300',       '003333', '003366', '003399', '0033CC', '0033FF', '006600', '006633', '006666', '006699', '0066CC'];
  var i = 0;
  var len = colors.length;
  var colorpicker = "";
  var a = colors.indexOf('000033');
 var b = colors.indexOf('003399');

  for (i = 0; i < len; i++) {

    if(a % 8 === 0){

        // begin row
            colorpicker += "<tr><td style='color:#"+colors[i]+"'>"+colors[i] +"</td>";
    }else if((b) % 8 === 0){
        // end row
            colorpicker += "<td style='color:#"+colors[i]+"'>"+colors[i] +"</td></tr>"
    }else{
        // midle of row
        colorpicker += "<td style='color:#"+colors[i]+"'>"+colors[i] +"</td>  ";
    }


}

document.getElementById("colorpicker").innerHTML = colorpicker;

The above will still result in a new row for each color. Any help will be greatly appreciated.

https://jsfiddle.net/ozhxzoph/

Is that what you meant to do? If so, you need to change "color" to "background-color".

Change this:

colorpicker += "<tr><td style='color:#"+colors[i]+"'>"+colors[i] +"</td>  </tr>";
}

To this:

colorpicker += "<tr><td style='background-color:#"+colors[i]+"'>"+colors[i] +"</td>  </tr>";
}

OR do you mean you want something like this? Where its a sort of grid of colors? The only difference here being that these are columns of 8, as opposed to rows of 8 which you seemed to be asking for.

https://jsfiddle.net/ozhxzoph/1/

Double Edit. Here is the solution for having 8 rows instead of 8 columns. The code has changed slightly more here though. Was a fun problem. :)

https://jsfiddle.net/ozhxzoph/6/

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM