如何使用javascript设置表td ids

时间:2015-05-21 05:48:27

标签: javascript

我正在处理一个表,我需要设置生成的行tds id。但我不知道怎么做。下面是两个td的html。我需要通过javascript函数设置id。

这是html:

<table id="myTable">
  <tr>
    <td onclick="myFunction()">Row1 cell1</td>
    <td>Row1 cell2</td>
  </tr>  
</table>

使用Javascript:

function myFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = "NEW CELL1";
    cell2.innerHTML = "NEW CELL2";
}

3 个答案:

答案 0 :(得分:0)

cell1.setAttribute("id", "id_1");
cell2.setAttribute("id", "id_2");

答案 1 :(得分:0)

setAttribute("id","idname"); 这会动态设置任何元素的id名称

答案 2 :(得分:0)

设置id属性

&#13;
&#13;
var rowCount = 0;
function myFunction() {
  var table = document.getElementById("myTable");
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  cell1.id = 'row' + ++rowCount + '-cell1'
  var cell2 = row.insertCell(1);
  cell2.id = 'row' + rowCount + '-cell2'
  cell1.innerHTML = "NEW CELL1";
  cell2.innerHTML = "NEW CELL2";
}
&#13;
<table id="myTable">
  <tr>
    <td onclick="myFunction()">Row1 cell1</td>
    <td>Row1 cell2</td>
  </tr>
</table>
&#13;
&#13;
&#13;