I have a javascript function which redirects user to a diff page. It goes like this...
redirect : function(url)
{
if(!url)
return false;
alert(url);
if (this.browserClass.isW3C) //IE 6.X comes here
{
window.location.href = 开发者_如何转开发url;
}
else if(this.browserClass.isIE4)
{
window.location.href = url;
}
else if (this.browserClass.isNN4)
{
window.location = url;
}
else
{
window.location = url;
}
return false;
},
But the problem is that this does not work in IE (internet explorer 6.X). After a short battle I saw that IE was redirecting when I change the code to this -
if (this.browserClass.isW3C)
setTimeout("location.href = '" +url+"'", 0);
Problem is solved. But what's going on here? Could someone educate me? or is it just one of those mind numbing idiosyncrasies of IE...
This function is a complete waste of time. Assignment to location.href
works equally well in all currently extant browsers. this.browserClass.isNN4
is a hint that this code is worrying about stuff that doesn't exist in this century. As if being stinky old browser-sniffing wasn't bad enough. (Anyway even in Netscape, both these assignments worked.)
setTimeout("location.href = '" +url+"'", 0);
Try not to pass strings to setTimeout
, it's the same thing as eval
with all the same problems (eg. your URL contains an apostrophe... boom). Pass a function, an inline one if necessary (setTimeout(function() { location.href= url; }, 0);
).
However what this smells like to me is you're trapping a click
or mousedown
event on a link, and not cancelling the event (by returning false
from the event handler). Consequently the link following default action can occur and may, depending on browser, override the location.href
navigation.
If you are not concern about the Web Browser keeping history (the back and forward buttons), just use the javascript location.replace(url)
function else you can always use the location.href
attribute.
Source: http://www.roseindia.net/javascript/javascript-location-replace.shtml
The window.location (if I remember correctly) is an object and not a string attribute.
I don't remember if document.location is still valid in IE6 though (I quit IE6 yonkers ago).
精彩评论