[英]JavaScript: How to change the background color of each td?
i have a table created by javascript. 我有一个由javascript创建的表格。 Every td of this big table contain an other table, now i need to change the background color of every td and with different colors of the big table, just likr this image image example how can i do that?
这个大表的每个td都包含另一个表,现在我需要更改每个td的背景色,并用大表的不同颜色,只是喜欢这个图像图像示例 ,我该怎么做? I hope u understand what i want.
我希望你明白我想要的。 Of course with javascript only
当然只有javascript
//Table de multiplication de 1 a 12 function tablede2(n){ var ch = "<table border='0'>",i; for(i=1;i<=10;i++){ ch = ch + "<tr><td width='30' align='center'>"+n+"</td><td width='30' align='center'>*</td><td width='30' align='center'>"+i+"</td><td width='30' align='center'>=</td><td width='30' align='center'>"+(i*n)+"</td></tr>"; } return ch +"</table>"; } function tableMult(){ var ch = "<table border='1' cellspacing='0'>",i, j,n; n=1; for(j=1; j<=4; j++){ ch += "<tr>"; for(i=1;i<=3;i++){ ch +="<td>"; ch += tablede2(n); n++; ch += "</td>"; } ch += "</tr>"; } ch += "</table>"; var elt = document.getElementById("p3"); elt.innerHTML = ch; }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Java Script</title> <script src="exo1_tpJS.js"></script> </head> <body> <button onclick="tableMult()">Table de multiplication de 1 a 12<em> avec innerHTML</em></button> <div id="p3">Table de multiplication de 2</div> </body> </html>
I think this fits your requirement. 我认为这符合您的要求。
1.Create a function to generate random colors 1.创建一个函数以生成随机颜色
2.call that function for every td and append as background-color 2.为每个td调用该函数并附加为背景颜色
//Table de multiplication de 1 a 12 function tablede2(n){ var ch = "<table border='0'>",i,bg; for(i=1;i<=10;i++){ if(i%2==0) bg='orange'; else bg='silver'; ch = ch + "<tr><td style='width='30' align='center'>"+n+"</td><td width='30' align='center'>*</td><td width='30' align='center'>"+i+"</td><td width='30' align='center'>=</td><td width='30' align='center'>"+(i*n)+"</td></tr>"; } return ch +"</table>"; } function tableMult(){ var ch = "<table border='1' cellspacing='0'>",i, j,n; n=1; for(j=1; j<=4; j++){ ch += "<tr>"; for(i=1;i<=3;i++){ var color=getBackgroundColor(); // console.log(color); ch +="<td style='background-color:"+color+"'>"; ch += tablede2(n); n++; ch += "</td>"; } ch += "</tr>"; } ch += "</table>"; var elt = document.getElementById("p3"); elt.innerHTML = ch; } function getBackgroundColor(){ var r = Math.floor(Math.random() * 255); var g = Math.floor(Math.random() * 255); var b = Math.floor(Math.random() * 255); var col = "rgb(" + r + "," + g + "," + b + ")"; return col; }
<button onclick="tableMult()">Table de multiplication de 1 a 12<em> avec innerHTML</em></button> <div id="p3">Table de multiplication de 2</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.