我已经通过 DOM 创建了表格,现在想为该表格添加样式,但它不起作用。 代码:
<script>
var nrCols=4;
var maxRows=10;
var nrRows=maxRows+1;
while(nrRows>maxRows)
{
nrRows=Number(prompt('How many rows? Maximum '+maxRows+' allowed.',''));
}
var root=document.getElementById('mydiv');
var tab=document.createElement('table');
var style=document.createElement('style');
style.setAttribute('background-color','red');
tab.appendChild(style);
tab.setAttribute('Border','1');
tab.className="mytable";
var tbo=document.createElement('tbody');
var tr1= document.createElement('tr');
var th1= document.createElement('th');
th1.appendChild(document.createTextNode('No.'));
var th2= document.createElement('th');
th2.appendChild(document.createTextNode('Surah.'));
tr1.appendChild(th1);
tr1.appendChild(th2);
tbo.appendChild(tr1);
var row, cell;
for(var i=0;i<nrRows;i++){
row=document.createElement('tr');
for(var j=0;j<nrCols;j++){
cell=document.createElement('td');
cell.appendChild(document.createTextNode('Allah'+' '+j))
row.appendChild(cell);
}
tbo.appendChild(row);
}
tab.appendChild(tbo);
root.appendChild(tab);
</script>
我使用了 style.setAttribute('background-color','red');
但没有区别。如何解决?
最佳答案
替换
var style=document.createElement('style');
style.setAttribute('background-color','red');
tab.appendChild(style);
与:
tab.style.backgroundColor = 'red';
所有元素都有一个样式属性,您可以向该属性添加适当的样式值。
关于javascript - 如何在动态创建的表中添加 'style'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20812292/