【问题标题】:JavaScript error: Uncaught TypeError: Cannot read property 'remove' of undefinedJavaScript 错误:未捕获的类型错误:无法读取未定义的属性“删除”
【发布时间】:2016-10-28 19:17:39
【问题描述】:

我有一个脚本可以在添加到成功后删除上传的文件,但是在加载时我在现场收到此错误。

"Uncaught TypeError: Cannot read property 'remove' of undefined"

缺少什么?

<script>
onload=function() {
    document.querySelectorAll("li[id^='uploadNameSpan']")[0].remove();
}
</script>

【问题讨论】:

  • 不应该是window.onload吗???
  • @David 这是一样的。
  • 没有符合您的选择器模式。
  • 选择器错误...或者在代码运行后添加了元素。如果是后者,则需要显示它们是如何添加的。所有失败原因的解释都无法让您找到使其工作的解决方案

标签: javascript dom


【解决方案1】:

基本上,您的问题是,在您调用此代码时,DOM 中没有与查询 "li[id^='uploadNameSpan']" 对应的任何元素。所以querySelectorAll 返回一个空的NodeList,其中undefined0 位置(或任何位置)。

正在发生的事情的细分:

var liElements = document.querySelectorAll("li[id^='uploadNameSpan']"); // this returns an empty NodeList

var nonExistentFirstElement = liElements[0]; // this is undefined, there's nothing at the first position

nonExistentFirstElement.remove(); // thus, this is an error since you're calling `undefined.remove()`

根据您的用例,您可以做的一件事是在尝试删除之前检查返回的项目数量:

var liElements = document.querySelectorAll("li[id^='uploadNameSpan']");
if (liElements.length > 0) {
  liElements[0].remove();
}

通常,您必须确保在尝试删除该元素时该元素在 DOM 中。

【讨论】:

  • this returns [] 不太准确……是 elementList 不是数组
  • @charlietfl 它类似于数组,与这个特定问题无关,但你是对的。我实际上已经先把它写下来,然后编辑问题以简化它。现在换回来了。
  • 这似乎很完美。没有脚本错误和应有的功能。非常感谢
  • 对我来说,我不得不使用 if( liElements != null ) 而不是 if(liElements.length > 0)
  • @PrabuddhaKulatunga 这可能是因为您使用了querySelector 而不是querySelectorAll
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
  • 2016-01-01
  • 2012-07-04
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多