最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Logging an error with offset().top, why? - Stack Overflow

programmeradmin1浏览0评论

I am trying to determine the top offset of an element and the console logs an error, even though JQuery's documentation says it should be written like this:

$('.myObject').offset().top

Error:

Uncaught TypeError: Cannot read property 'top' of undefined

Why does this happen? Any solution for the problem?

I am trying to determine the top offset of an element and the console logs an error, even though JQuery's documentation says it should be written like this:

$('.myObject').offset().top

Error:

Uncaught TypeError: Cannot read property 'top' of undefined

Why does this happen? Any solution for the problem?

Share Improve this question edited Oct 25, 2013 at 7:12 zzlalani 24.4k16 gold badges47 silver badges73 bronze badges asked Oct 25, 2013 at 7:07 gespinhagespinha 8,50717 gold badges59 silver badges96 bronze badges 3
  • 1 what does $('.myObject').length returns? – Saturnix Commented Oct 25, 2013 at 7:08
  • 2 Are you sure it isn't $('#myObject')? Using a class selector may be returning a set instead of one element. – Abhitalks Commented Oct 25, 2013 at 7:09
  • If called on a set, .offset() will return the offset of the first element so it should not crash anyway. – Saturnix Commented Oct 25, 2013 at 7:27
Add a ment  | 

2 Answers 2

Reset to default 4

This usually happens because $('.myObject') returns nothing. To protect your code from crashing, check if the element exists before calling .offset().top

var myObj = $('.myObject');
if (myObj.length){
   myObj.offset().top
}

Since .top is a property and not a method, it is not handled by jQuery and, hence, will crash your script if it is not existing.

You'll have to check if the element exists.

e.g.

var myObjExists = $('.myObject').length > 0 ? true : false;

if you then console.log(myObjExists);, it should return true or false.

From here you can do some errorhandling to why it does not exist.

If you need more details, please also post the HTML that this code points to.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论