Ich versuche, jeder Zeile, die dynamisch eine eindeutige ID hinzugefügt wird. Grundsätzlich, indem jedes Mal, wenn der Benutzer auf die Schaltfläche Hinzufügen klickt, die Zahl zu der Zahl hinzugefügt wird. Es fügt eine ID hinzu, aber nicht korrekt, es wird in den Entwicklungstools als "undefiniert" angezeigt.JavaScript setAttribute ID zu Zeile ist nicht definiert
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>
Verwenden Sie '.id' anstelle von' .setAttribute ('id', ...) '. Und was ist "Stil"? CSS ??? –
Sie scheinen nur ein Argument an 'appendRow()' zu übergeben, obwohl es zwei dauert. Dies führt dazu, dass "Stil" undefiniert ist. – abagshaw
@ibrahimmahrir Es gibt kein Problem mit 'setAttibute' mit' id', wenn Sie möchten. –