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

javascript - Why does "window = window.parent;" create an infinite loop? - Stack Overflow

programmeradmin7浏览0评论

I was traversing through a frame hierarchy, and tried the following to find the top frame:

var win = window;
while (win.parent) {
    //perform actions on win
    win = win.parent;
}

By now, I know that the correct looping condition must be:

while (win !== top) {

The existence check on win.parent seemingly creates an infinite loop. Is there any particular reason why it is like this? Why should top have a parent?

I was traversing through a frame hierarchy, and tried the following to find the top frame:

var win = window;
while (win.parent) {
    //perform actions on win
    win = win.parent;
}

By now, I know that the correct looping condition must be:

while (win !== top) {

The existence check on win.parent seemingly creates an infinite loop. Is there any particular reason why it is like this? Why should top have a parent?

Share Improve this question asked Mar 23, 2012 at 10:35 Stefan MajewskyStefan Majewsky 5,5553 gold badges32 silver badges51 bronze badges 2
  • Have you tried to check what's top.parent ? – Madara's Ghost Commented Mar 23, 2012 at 10:39
  • Perhaps that is how 'top' is flagged - maybe the top frame has itself as a parent? – Martin James Commented Mar 23, 2012 at 10:40
Add a ment  | 

2 Answers 2

Reset to default 7

You should also check if window.parent == window​ is false. Otherwise you will end up with an infinite loop. If there is no parent, the parent property will reference to itself (infinite loop).

var win = window;
while (win.parent && win.parent != win) {
    //perform actions on win
    win = win.parent;
}​

http://jsfiddle/EZfHf/

I found this on MDN:

If a window does not have a parent, its parent property is a reference to itself.

top's parent is itself.

top == top.parent //true
发布评论

评论列表(0)

  1. 暂无评论