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

Ron*_*nni 7 javascript dom

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

"Uncaught TypeError: Cannot read property 'remove' of undefined"
Run Code Online (Sandbox Code Playgroud)

少了什么东西?

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

nem*_*035 12

基本上,您的问题是,在调用此代码时,DOM 中没有任何与 query 对应的元素"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()`
Run Code Online (Sandbox Code Playgroud)

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

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

一般来说,您必须确保在尝试删除该元素时该元素已存在于 DOM 中。