【发布时间】:2018-04-26 13:52:21
【问题描述】:
我试图给动态添加的每一行一个唯一的 ID。基本上是在用户每次单击添加按钮时添加数字。它正在添加一个 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>
【问题讨论】:
-
使用
.id而不是.setAttribute('id', ...)。style是什么? CSS??? -
您似乎只将一个参数传递给
appendRow(),即使它需要两个。导致style未定义。 -
@ibrahimmahrir 如果您愿意,可以使用
setAttibute和id没有问题。 -
在 appendRow() 我有 (id, style) 所以是两个,为什么它不起作用?
-
@ibrahimmahrir .id 工作,谢谢!
标签: javascript html setattribute unique-id