javascript - 当我使用 innerHTML 时返回未定义
问题描述
<script>
window.onload=function(){
var allA = document.getElementsByTagName("a");
for(var i=0;i<allA.length;i++){
allA[i].onclick=function(){
alert("Are you sure to delect the "+
this.parentNode.parentNode.firstChild.innerHTML+"?");
tr.parentNode.removeChild(tr);
return false;}
}
};
</script>
<body>
<tr id="Tlist">
<th>A</th>
<the>B</th>
<th>C</th>
<td><a href="javascript">Select</a></td>
</tr>
</body>
上面的代码是 HTML 文件的一部分,当我点击 Select 时,我使用 parenNode.ParenNode 获取 Tlist,并使用 firstChild 获取 A,如果代码没有 innerHTML,它将显示整个 Twist,所以我认为我做了正确的事情来获得 Tlist。但是,当我使用 innerHTML 尝试获取 first 中的文本时,这表明我未定义。
解决方案
使用firstElementChild
而不是firstChild
. firstChild
将返回一个文本节点,在这种情况下是第一个<th>
. 使用firstElementChild
跳过文本节点。
window.onload = function() {
var allA = document.getElementsByTagName("a");
for (var i = 0; i < allA.length; i++) {
allA[i].onclick = function() {
var tr = this.parentNode.parentNode;
alert("Are you sure to delect the " +
tr.firstElementChild.innerHTML + "?");
tr.parentNode.removeChild(tr);
return false;
}
}
};
<table>
<tr id="Tlist">
<th>A</th>
<th>B</th>
<th>C</th>
<td><a href="javascript:void(0)">Select</a></td>
</tr>
</table>
推荐阅读
- git - 将 --autosquash 传递给 git pull --rebase=interactive
- javascript - 如何在没有滚动行为的情况下转到特定部分/没有滚动行为的 scrollIntoView() 的任何替代方法?
- java - if-else 一行语句(带字符串和整数)
- c# - Blazor 绑定到预填充列表并将选择作为列表发送回
- c# - 电报机器人 - 错误请求:文件必须非空
- c - C中的Unix网络编程
- angular - 2021 年 9 月 1 日 Angular 中的日期格式
- javascript - 将函数作为对象字面量返回
- python - 按值的顺序获取字典的键
- javascript - 我需要使用匹配的键删除对象列表。(例如键有 1 和 2 ,结果只会显示 3)