【发布时间】:2021-12-21 22:06:09
【问题描述】:
我有一个 js 脚本,它正在提取一个类的内部文本。有时该类不会在网页上呈现,因此对于这种情况,innertext 是未定义的。我想对此进行检查,以便省略此错误。 这是我写的代码->
function myfunc() {
var button = document.getElementsByClassName('myclass');
if (button[0].innerText !== undefined) {
console.log(button[0].innerText);
clearInterval(x);
}
}
var x = setInterval(function() {
myfunc();
}, 1)
因此,对于页面上不存在该类的情况,我收到了一个未定义的错误,因此我想检查一下。我通过检查它是否为!== undefined 在代码中使用了if 条件,但这不起作用。任何人都可以建议一些其他方法吗?我得到的错误->
Uncaught TypeError: Cannot read property 'innerText' of undefined
【问题讨论】:
-
if(button[0]) {...}可能会起作用。目前,您正在尝试访问不适合您的条件的元素的文本。 -
或者尝试使用
button[0]?.innerText(注意?)这首先检查按钮[0]是否存在
标签: javascript undefined setinterval innertext