为什么我得到“;未捕获的类型错误:无法读取属性“”;此变量出错
Why do I get "Uncaught TypeError: Cannot read property" error with this variable?
在这个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值的属性,该属性将引发异常。
相关文章:
- TypeError:无法读取属性'推'未定义的JavaScript
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 未捕获的类型错误:无法读取属性'删除'的未定义
- AngularJS指令出错-无法读取属性'编译'的未定义
- 未捕获的类型错误:无法读取属性'name'即使它存在,也无法定义
- 看到“;未捕获的类型错误:无法读取属性'weight'未定义的“;尽管按照字面上的指示
- 无法读取属性'材料'未定义的Three.js
- 得到"TypeError:无法读取属性'filename'未定义的“;调用“npm start
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- 未捕获的类型错误:无法读取属性'addEventListener'的null chrome扩展名
- Soundcloud Javascript SDK 3.0-回调无法读取属性'connectCallback
- 未捕获的类型错误:无法读取属性'状态'在react中为null
- JavaScript承诺-无法读取属性'那么'的未定义
- Javascript Float32数组抛出无法读取属性'0'即使数组定义良好,也为null
- 未捕获的类型错误:无法读取属性'中止'的未定义
- 角度推入数组给出:TypeError:无法读取属性'推'的未定义
- http/rxjs catch回调中的Angular 2重定向导致TypeError:无法读取属性'订阅'
- Javascript未捕获类型错误:无法读取属性'0'的未定义
- jQuery控制台错误:无法读取属性'top'的未定义
- TypeError:无法读取属性'findAll'的未定义