動的に追加された各行に一意のIDを付与しようとしています。基本的には、ユーザーが追加ボタンをクリックするたびに番号に追加します。 IDを追加していますが、正しくはありませんが、開発ツールでは「未定義」と表示されています。JavaScript setAttributeの行IDが未定義
var counter = 0;
function appendRow(id, style) {
var table = document.getElementById(id); // table reference
length = table.length,
row = table.insertRow(table.rows.length, 'id'); // append table row
row.setAttribute('id', style);
row.setAttribute('idName', style);
var i;
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'cust' + counter);
counter++
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
table {
text-align: center;
}
td {
width: 100px;
}
tr:nth-child(even) {
background-color: #fff;
}
tr:nth-child(odd) {
background-color: #eee;
}
<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>
<div class="custScroll">
<table id="custListTop" contenteditable="false">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>Somewhere</td>
</tr>
</table>
</div>
'.setAttribute( 'id'、...)'の代わりに '.id'を使います。 「スタイル」とは何ですか? CSS ??? –
2つではありますが、1つの引数を 'appendRow()'に渡しているようです。結果として、 'style'は未定義です。 – abagshaw
@ibrahimmahrirあなたがしたい場合は 'id'で' setAttibute'を使っても問題ありません。 appendRow()内の –