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

javascript - jQuery $(this).position().top not working in Chrome - Stack Overflow

programmeradmin3浏览0评论

I was wondering if there would be any reason this piece of code will not work...

top = $(this).find('ul').position().top;

It works in IE, Firefox, and Safari, however when I alert the output in Chrome it says DOM window object... I need an integer. Why would it alert out DOM window object?

I was wondering if there would be any reason this piece of code will not work...

top = $(this).find('ul').position().top;

It works in IE, Firefox, and Safari, however when I alert the output in Chrome it says DOM window object... I need an integer. Why would it alert out DOM window object?

Share Improve this question edited Jun 21, 2011 at 4:25 Greg 23.5k11 gold badges60 silver badges80 bronze badges asked Jun 21, 2011 at 4:23 Travis PessettoTravis Pessetto 3,2984 gold badges28 silver badges55 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

Are you sure you're really alerting that top? Recall that top is a pre-existing global variable in browser-hosted JavaScript (it's window.top, the top-level window).

Update: Interesting, Chrome won't let you implicitly overwrite top (which is probably a good thing): Demo. Just declare your variable (always a good idea anyway) within whatever function that code is in (that code is in a function, right?), which will shadow it, and so that will work: Demo. E.g.:

var top = $(this).find('ul').position().top;

It's important to declare your variables, in order to avoid falling prey to the Horror of Implicit Globals. And as you've found in this case, avoiding globals is always best, as Chrome won't even let you use top as a global if you declare it (again to protect window.top).

Make sure you are assigning the value to a locally scoped variable. Use the var keyword.

var top = $(this).find('ul').position().top;
发布评论

评论列表(0)

  1. 暂无评论