首页 > 解决方案 > 当我使用 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 中的文本时,这表明我未定义。

标签: javascripthtml

解决方案


使用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>


推荐阅读