동적으로 추가 된 각 행에 고유 ID를 부여하려고합니다. 기본적으로 사용자가 추가 버튼을 클릭 할 때마다 번호에 추가됩니다. 그것은 ID를 추가하고 있지만 정확하게는 "정의되지 않은"dev 도구로 나타나고 있습니다.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 ??? –
두 개를 취하는 경우에도 하나의 인수 만'appendRow()'에 전달하는 것처럼 보입니다. 결과적으로'style'이 정의되지 않았습니다. – abagshaw
@ibrahimmahrir 원하는 경우'id'와 함께'setAttibute'를 사용하는 데 문제가 없습니다. appendRow()의 –