2011-05-21 109 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