IE javascript redirection

只谈情不闲聊 提交于 2019-12-25 02:31:56

问题


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...


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/2098758/ie-javascript-redirection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!