javascript 动态添加表格行时如何更改td.style
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18334369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change td.style when dynamic add table row
提问by Shuinvy
I use JavaScript to add table rows dynamically, but I don't know how to change the style of the table data. My code is:
我使用JavaScript动态添加表格行,但不知道如何更改表格数据的样式。我的代码是:
var tableis = document.getElementById("cameraTable");
var last=(-1);
var Tr = tableis.insertRow(last);
var Td1 = Tr.insertCell(0);
Td1.innerHTML="<div name='mac"+i+"' id='mac"+i+"'>"+mac+"</div>";
Tr.appendChild(Td1);
and I only know how to change the background of the td:
我只知道如何更改 td 的背景:
Td1.bgColor="#00FF00";
I want to change the border style of the td, is it possible? The style is like:
我想改变td的边框样式,可以吗?风格是这样的:
style="border: 1px solid black;"
I have tried Td1.style="border: 1px solid black;"
but it is no effort.
我试过了,Td1.style="border: 1px solid black;"
但没有努力。
Any answer appreciated.
任何答案表示赞赏。
回答by pala?н
You can do this using the HTMLElement.style
:
您可以使用以下方法执行此操作HTMLElement.style
:
Td1.style.border = '1px solid black';
回答by flakomalo
I think a more elegant solution would be to have the CSS class defined rather than hard-coding the style in the cell.
我认为更优雅的解决方案是定义 CSS 类,而不是在单元格中硬编码样式。
/* CSS Class */
.cellStyle{
border: 1px solid black;
background-color: #00FF00;
}
/* JavaScript Code */
Td1.className = 'cellStyle';