![](/img/trans.png)
[英]How do I change background color of each list item with JavaScript?
[英]How do I iterate through the elements of a table and change the background color of each element in JavaScript?
我已經看過以前的答案,如何遍歷一個表,但我無法使其正常工作。 我一定在做蠢事。 這是一個例子:
我在CSS中有這個
td{width: 30px; height: 30px;
}
<body onload = "setBackground();">
<table id = "table1">
<tr id = "row1">
<td>Stack</td>
<td>Overflow</td>
<td>Is my life saver</td>
</tr>
</table>
</body>
現在,在JS中我有這個
function setBackground() {
var table = document.getElementById("table1");
//i found this in a previous stack overflow answer and tried it
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
//this is for debugging purposes... I can't even get this to work
alert(table.rows[i].cells[j]);
table.rows[i].cells[j].style.background = "orange"; //just an example
}
}
}
請注意,我在body標簽中調用了該函數,但這不起作用。 我一直在試圖解決這個問題,但我做不到! 另外,我也不了解JQuery。 如果有人可以幫助我,我將不勝感激。
不使用jQuery:
(function() {
function setBackground() {
var table = document.getElementById("table1");
//i found this in a previous stack overflow answer and tried it
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
//this is for debugging purposes... I can't even get this to work
alert(table.rows[i].cells[j]);
table.rows[i].cells[j].style.background = "orange"; //just an example
}
}
}
setBackground();
})();
而且您不需要body onload
在這里,您會找到: http : //jsfiddle.net/h7ks4/
如果您願意使用jQuery,可以嘗試以下操作:
$('#table1 td').css('background', 'orange');
但是,如果您想執行一些更復雜的操作,請嘗試.each
函數
$('#table1 td').each(function(){
$(this).css('background', 'orange');
//or plain javascript if you prefer
this.style.background = 'orange';
});
.each
將遍歷所有td
並且函數內部的this
關鍵字將引用當前循環的td
。
為什么不使用javascript創建表??? jsbin演示
<div id="tableContainer" >
</div>
<script>
function setTable() {
var tableCntr= document.getElementById('tableContainer') ;
var tblHTML = "<table>" ;
var colors = [['red','blue','green'],['orange', 'black', 'purple']] ;
for(var i=0;i<colors.length;i++) {
tblHTML +="<tr>";
for(var j=0;j<colors[0][0].length;j++) {
tblHTML += "<td style='background:" + colors[i][j] + "'> </td>" ;
}
tblHTML += "</tr>" ;
}
tblHTML +="</table>" ;
console.log(tblHTML);
tableCntr.innerHTML = tblHTML ;
}
window.onload = setTable;
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.