JavaScript Get the child id
JavaScript Get the child id
我正在尝试向表添加新行,如下所示:
<table class="table table-striped">
<tbody id="dconTable">
<th><input type="text" class="span12" id="lbld"></th>
<th><input type="text" class="span12" id="edizmd"></th>
<th><input type="text" class="span12" id="idd"></th>
<th><input type="text" class="span12" id="ad"></th>
<th><input type="text" class="span12" id="bd"></th>
<th><input type="text" class="span12" id="en_spard"></th>
<th><input type="text" class="span12" id="spard"></th>
<th><input type="text" class="span12" id="en_periodd"></th>
<th><input type="text" class="span12" id="periodd"></th>
</tbody>
</table>
我使用我在互联网上找到的脚本。我希望他也在新单元格中写id(如id="lbld_1"等)。这是代码。
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
colName = table.rows[0].cells[i].parentNode.children[1].getAttribute('id') +"_"+ i;
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
newcell.childNodes[0].value = "";
newcell.parentNode.children[1].setAttribute('id',colName);
colName = "";
}
};
控制台 说:
Uncaught TypeError: Cannot call method 'setAttribute' of undefined
请告诉我我的错误。谢谢。
你的代码对我来说没有任何意义:
table.rows[0].cells[i].parentNode.children[1];
//===
table.rows[0].cells[1];
单元格是行的子级,所以获取一行的 parentNode,它将返回一行,获取它的子级之一,然后你又回到了单元格的级别(如果你幸运的话!- 一些浏览器会在节点列表中包含空格或注释)。
此外,如果您需要身份证,只需anElem.id
就可以了,getAttribute()
有点多。
所以这将是你要做的:
colName = table.rows[0].cells[i].id;
newcell.id = colName;
但这是在创建具有相同ID的多个元素,这是不可能的。在现实生活中,如果别人有我的身份证,我就会遇到问题。同样的逻辑也适用于DOM中的ID:它们是唯一的!所以试试:
colName = table.rows[0].cells[i].id.split('_')[0];
newcell.id = colName+'_'+i;
最后,您似乎没有附加元素,因此也添加table.rows[0].appendChild(newCell);
相关文章:
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- difference between '$(<%= DDL.ID %>) & $('
- 使用Javascript获取所选选项ID
- 根据id将json数组组合为一个json数组
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 对id以某个字符串开头的元素进行计数
- 如果元素's的ID以数字开头
- 通过id和class属性获取元素
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- 使用当前日期生成随机id
- Javascript-ID冲突的几率
- Href:当前DIV中的目标ID
- 无法获取属性'Id'使用Knockout.js的未定义或空引用API
- Javascript复选框函数:;缺少:在属性id之后"
- Twitter引导程序Typeahead-Id&标签
- 如何与特定ID交谈
- chart.series[id].remove()无法刷新高位图表/高位股票中其他系列的图例属性
- JavaScript Get the child id
- Id没有在child.eval中定义
- 当我们点击child复选框时,如何获得父对象的父id