jQuery追加div

时间:2011-05-21 13:44:28

标签: jquery

我想将div添加到父div,每个较小的div是从数组中选择的随机背景颜色。我该怎么做?

我已经拥有的东西:

$(document).ready(function(){

    var cell_size = 10;
    var container = $("#container");
    var colors = ["limepulp", "goldgreen", "chromeoxidegreen", "kermit", "pear"];

    /* Get the cell dimentions and populate the grid */
    var cell_height_num = container.height() / cell_size;   /* This is equal to 50 */
    var cell_width_num = container.width() / cell_size;     /* This is also equal to 50 */

    for (var i = 0; i < cell_width_num * cell_height_num; i++){

         /* What goes here? How can I generate a div with a random background comming from colors[]? */
         /* In total, 2500 divs should be generated inside $("#container"); */

    }

});

2 个答案:

答案 0 :(得分:1)

var colors = [ 'red', 'blue', 'green', '#ffe' ];
...
for (var i = 0; i < cell_width_num * cell_height_num; i++) {
    var color = colors[Math.floor(Math.random() * colors.length)];
    $('#container').append(
        $('<div/>', {
            style: 'background-color:' + color,
            text: 'some text'
        })
    );
}

另请注意,colors数组中包含的颜色不是有效的CSS颜色名称。您可以使用#RGB等效项来定义它们。

答案 1 :(得分:0)

这更适合<table>

Live example

代码:

/* Get the cell dimentions and populate the grid */
var cell_height_num = 50; /* This is equal to 50 */
var cell_width_num = 50; /* This is also equal to 50 */
for (var i = 0; i < cell_height_num; i++) {
    var tr = $("<tr></tr>").appendTo(container);
    for (var j = 0; j < cell_width_num; j++) {
        tr.append($("<td></td>", {
            css: {
                width: "1px",
                height: "1px",
                backgroundColor: colors[Math.floor(Math.random() * colors.length)]
            }
        }));
    }
}
相关问题