javascript jQuery $(this).position().top 在 Chrome 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6420323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery $(this).position().top not working in Chrome
提问by Travis Pessetto
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?
它适用于 IE、Firefox 和 Safari,但是当我在 Chrome 中提醒输出时,它说 DOM 窗口对象...我需要一个整数。为什么它会提醒 DOM 窗口对象?
回答by T.J. Crowder
Are you sure you're really alerting thattop
? Recall that top
is a pre-existing global variable in browser-hosted JavaScript (it's window.top
, the top-level window).
你确定你真的在提醒那个top
吗?回想一下,这top
是浏览器托管的 JavaScript 中预先存在的全局变量(它是window.top
,顶级窗口)。
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 isin a function, right?), which will shadowit, and so that will work: Demo. E.g.:
更新:有趣的是,Chrome 不会让您隐式覆盖top
(这可能是一件好事):Demo。只要你声明变量中的任何功能的代码是(代码(总是一个好主意,反正)是一个函数,对吧?),这将影吧,等,将工作:演示。例如:
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
).
声明变量很重要,以避免成为隐式全局变量的牺牲品。正如您在这种情况下发现的那样,避免全局变量总是最好的,因为top
如果您声明它(再次保护window.top
),Chrome 甚至不会让您用作全局变量。
回答by Greg
Make sure you are assigning the value to a locally scoped variable. Use the var
keyword.
确保将值分配给本地范围的变量。使用var
关键字。
var top = $(this).find('ul').position().top;