javascript 将属性设置为动态生成的 <td> 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7647141/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:47:53  来源:igfitidea点击:

Set attribute to dynamically generated <td> tag

javascripthtmlcssjavascript-events

提问by Muhammad Imran Tariq

I am adding dynamic row to table through javascript.

我正在通过 javascript 向表中添加动态行。

var cell1 = row.insertCell(0);

var element2 = document.createElement('input');    
element2.value = "valueHere";
element2.type = "text";

cell1.appendChild(element2);

It creates new row in table.

它在表中创建新行。

<tr>
 <td>
  <input type="text" value="valueHere">
 </td>
</tr>

I want to add a class to tag. e.g. <td class="styleClass">

我想添加一个类 标签。例如<td class="styleClass">

回答by lonesomeday

You need to set the classNameproperty of the table cell (cell1):

您需要设置className表格单元格的属性 ( cell1):

cell1.className = 'styleClass';

回答by Jan Pfeifer

To add a class to a cell/TD

将类添加到单元格/TD

var cell1 = row.insertCell(0);
    cell1.className = 'styleClass';
    //cell1.style = ... whatever you want
...
rest of your code