【问题标题】:Checking if innerText of class is defined or not检查类的 innerText 是否已定义
【发布时间】: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


【解决方案1】:

这不起作用,因为document.getElementsByClassName('myclass') 返回 0 个按钮,所以 button[0] 已经未定义。

您可以通过使用可选链接来解决这个问题:

if(button[0]?.innerText !== undefined){

如果? 之前的某些内容未定义,则左侧的值将自动未定义。

如果button[0] 不存在/未定义,JS 甚至不会尝试获取innerText 属性。

甚至更简单

只检查长度:

if(button.length > 0) {

【讨论】:

    【解决方案2】:

    您只需要在尝试innerText 之前检查button[0] 是否存在。我清理了一下,但这应该可以解决问题:

    function checkForButton() {
       const button = document.querySelector('.myclass');
       if (button && button.textContent) {
         console.log(button.textContent);
         clearInterval(x);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多