为什么我得到“;未捕获的类型错误:无法读取属性“”;此变量出错

Why do I get "Uncaught TypeError: Cannot read property" error with this variable?

本文关键字:读取 属性 出错 变量 类型 为什么 错误      更新时间:2023-09-26

在这个jsFiddle中,我有两个变量,它们要么是未定义的,要么是null。如果初始化了第一个变量,脚本就会工作,但如果使用了第二个变量,则不会工作。您可以通过注释每一个并运行脚本来测试这一点。

这是代码:

var test = $('.not-here').height(); // works with this variable
var test2 = $('.also-not-here').offset().top; // doesn't work with this
$('#output').append('yeah');

为什么我会遇到这个问题,我该如何解决它?

两个选择器都无效,因此它们返回一个空的jQuery结果列表。

在空的结果列表上调用.height()会返回null。在空的结果列表上调用.offset()也返回null

在第二行中得到Uncaught TypeError: Cannot read property 'top' of null的原因是,您正试图对offset()的结果调用.top(),即null

基本上,您正在尝试执行null.top()

我不知道你的代码是用来做什么的,但作为一个纯粹的例子,你可以在使用它们之前先检查结果,类似于这样:

var $elem1 = $('.not-here');
var $elem2 = $('.also-not-here');
if($elem1.length && $elem2.length){
    var test = $elem1.height();
    var test2 = $elem2.offset().top;
    $('#output').append('yeah');
}
如果节点不存在,则$('.also-not-here').offset()返回null。这就是它的设计原理。

如果你想要一个修复程序,这样你的代码就不会崩溃,你可以这样做:

var $node = $('.also-not-here');
var test2 = $node.length>0 ? $node.offset().top : null;
var test = $('.not-here').height();

这会返回null,因为没有元素$('.not-here')

再次,

var test2 = $('.also-not-here').offset();

这也会返回null,因为没有元素$('.also-not-here'),并且我们无法读取null的属性top

我建议这样做:

$.fn.isThere = function(){ return this.length > 0; }
var $selector = $('.also-not-here');
if ($selector.isThere()) {
    var test2 = $selector.offset().top;
}

第一个test被设置为null。第二种情况是,您试图引用一个null值的属性,该属性将引发异常。