我有一个脚本可以在添加成功后删除上传的文件,但是当它加载时我在网站上遇到了这个错误。
"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在 0
位置(或与此相关的任何位置)有 undefined
。
发生的事情的分解:
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 中。
关于JavaScript 错误 : Uncaught TypeError: Cannot read property 'remove' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38042716/