JavaScript 错误:未捕获的类型错误:无法读取未定义的属性“删除”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38042716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:01:25  来源:igfitidea点击:

JavaScript error: Uncaught TypeError: Cannot read property 'remove' of undefined

javascriptdom

提问by Ronni

I have a script to remove uploaded files after Add to success, but I get this error on site when it loads.

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

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

What's missing?

缺少了什么?

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

采纳答案by nem035

Basically, your issue is that, at the time you call this code, you don't have any elements in the DOM corresponding to the query "li[id^='uploadNameSpan']". So querySelectorAllreturns an empty NodeListwhich has undefinedat the 0position (or any position for that matter).

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

Breakdown of what is happening:

正在发生的事情的细分:

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()`

Depending on your use case, one thing you can do is have a check for the amount of items returned before trying to remove:

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

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

In general, you have to make sure to have the element in the DOM at the time you are trying to remove it.

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