当元素不存在时"Cannot read property"如何避免错误?



这是我的代码:

category = $(document).find(".chosen-single:not(.chosen-default)  > span:first-child")[0].outerHTML

有时它会抛出:

捕获的类型错误:无法读取未定义的属性"outerHTML">

我应该在路上提出什么样的条件?

一个不错的技巧是使用匿名函数,如下所示,将查询作为参数传递

category = (function (el) {
             return (el) ? el.outerHTML : '';
           })($(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0]);

它将节省您设置额外变量和 if/then/else 语句的时间。

使代码看起来像这样:

var element = $(document).find(".chosen-single:not(.chosen-default)  > span:first-child")[0];
if(element) {
   category = element.outerHTML
}

似乎有时您正在搜索的元素丢失了,因此结果未定义,为避免此问题,请检查是否找到了您查询的内容

检查本机 DOM 元素或检查 jQuery 对象的长度:

var obj = $(document).find(".chosen-single:not(.chosen-default)  > span:first-child")[0];
var category = "";
if (obj) category = obj.outerHTML;

检查长度:

var $obj = $(document).find(".chosen-single:not(.chosen-default)  > span:first-child");
var category = "";
if ($obj.length) category = obj.outerHTML;

只需将元素存储在变量中,然后在访问之前对其进行检查:

var $chosenItem = $(document).find(".chosen-single:not(.chosen-default)  > span:first-child")[0];
category = $chosenItem && $chosenItem.outerHTML;

或者替换您选择的条件。

创建一个变量来计算该特定类的元素数,然后创建一个 if 语句。

例如:

   var chosenClass = document.querySelectorAll('.chosen-single').length;
   if(chosenClass == 0) {
      null;
   }
     else {   
     }

相关内容

最新更新