这是我的代码:
category = $(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0].outerHTML
有时它会抛出:
Uncaught TypeError: Cannot read property 'outerHTML' of undefined
我应该为此设置什么样的条件?
最佳答案
一个不错的技巧是使用匿名函数,就像这样,将查询作为参数传递
category = (function (el) {
return (el) ? el.outerHTML : '';
})($(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0]);
它将节省您设置额外变量和 if/then/else 语句的麻烦。
关于javascript - 当元素不存在时如何避免 "Cannot read property"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49257289/