JavaScript 错误:未捕获的类型错误:无法读取未定义的属性'remove'



我有一个脚本删除上传的文件后添加到成功,但我得到这个错误在网站上当它加载

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

缺失的是什么?

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

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

详细说明:

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中

最新更新