Difference between window.location.href and top.location.href
Can Anyone te开发者_开发问答ll me the difference between window.location.href
and top.location.href
?
And also where to use which one.
And which one will be better when redirecting after an ajax call in mvc?
window.location.href
returns the location of the current page.
top.location.href
(which is an alias of window.top.location.href
) returns the location of the topmost window in the window hierarchy. If a window has no parent, top
is a reference to itself (in other words, window
=== window.top
).
top
is useful both when you're dealing with frames and when dealing with windows which have been opened by other pages. For example, if you have a page called test.html
with the following script:
var newWin=window.open('about:blank','test','width=100,height=100');
newWin.document.write('<script>alert(top.location.href);</script>');
The resulting alert will have the full path to test.html – not about:blank, which is what window.location.href
would return.
To answer your question about redirecting, go with window.location.assign(url);
top
object makes more sense inside frames. Inside a frame, window
refers to current frame's window while top
refers to the outermost window that contains the frame(s). So:
window.location.href = 'somepage.html';
means loading somepage.html
inside the frame.
top.location.href = 'somepage.html';
means loading somepage.html
in the main browser window.
Two other interesting objects are self
and parent
.
The first one adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.
The second replaces the current history item so you can't go back to it.
See window.location
:
assign(url)
: Load the document at the provided URL.replace(url)
: Replace the current document with the one at the provided URL. The difference from theassign()
method is that after usingreplace()
the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
window.location.href = url;
is favoured over:
window.location = url;
top
refers to the window object which contains all the current frames ( father of the rest of the windows ). window
is the current window
.
http://www.howtocreate.co.uk/tutorials/javascript/browserinspecific
so top.location.href
can contain the "master" page link containing all the frames, while window.location.href
just contains the "current" page link.
精彩评论