Javascript - thing.length 不起作用 - 未捕获的类型错误

问题描述 投票:0回答:1

我发现了一个计算元素的直接子元素的函数。但是,每当我运行它时,控制台都会显示“未捕获的类型错误:无法读取未定义的属性(读取“长度”)”。我也在 VS code 中对此进行编码,并且代码编辑器中不会弹出错误。我必须转到选项卡,ctrl+i,然后查看控制台。
我不知道发生了什么(它应该可以正常工作),但这是我的代码:

function countChildElements(parent) {
  var children = parent.childNodes, cnt = 0;
  for (var i = 0, len = children.length; i < len; i++) {
    if (children[i].nodeType === 1) {
      cnt++;
    }
  }
  return(cnt);
}

function thing(ev) {
  alert(countChildElements(ev));
}
<a onclick="thing(event)">
  <p>hi</p>
  <p>2 children in this element (including this)</p>
</a>

有人知道为什么会这样吗?
附言。我无法在任何地方使用 .length 东西。它总是犯同样的错误。

javascript
1个回答
0
投票

改变一下事情

function thing(ev) {
  alert(countChildElements(ev.target.parentNode));
}
© www.soinside.com 2019 - 2024. All rights reserved.