2011-05-21 74 views
0

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

我已经有了:

$(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"); */ 

    } 

}); 
+0

这在某些机器上会很慢... 2500个div很多。我认为你应该考虑使用'帆布' – Hogan 2011-05-21 13:48:47

+0

这是一个div的crapload。这可能更适合服务器端... – 2011-05-21 13:48:57

+0

@Hogan大约需要200ms来呈现给我。 – Raynos 2011-05-21 14:02:23

回答

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)] 
      } 
     })); 
    } 
} 
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等价物来定义它们。

+0

他们可能是CSS类名... – 2011-05-21 13:54:27

+0

@Jason McCreary,是的,他们可能会。在这种情况下,代码可以很容易地使用'class'而不是'style'。 – 2011-05-21 13:55:36

+0

当然。只是把它放在那里为未来的访客。 – 2011-05-21 13:57:13