关于location.href几种用法的区别

常见的几种开发形式:

self.location.href;
window.location.href;
this.location.href;
location.href;
parent.location.href;
top.location.href; 

经常见到的大概有以上几种形式.

通过实际的例子讲解以上的几种形式有什么具体的区别:

总共是4个具体的HTML页面:

a.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html> 
<head> 
<title>这是a.html页面</title> 
<meta http-equiv="content-type" content="text/html; charset=gb2312"> 
</head> 
<body> 
<form id="form1" action="">
<div><strong>这是a.html页面<strong>
<iframe src="b.html" width="500px" height="300px"></iframe> </strong></strong></div>
</form>
</body> 
</html>

b.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html> 
<head> 
<title>这是b.html</title> 
<meta http-equiv="content-type" content="text/html; charset=gb2312"> 
</head> 
<body> 
<span>这是b.html</span><span id="span1"></span><br />
<iframe src="c.html" width="500px" height="300px"></iframe>
</body> 
</html>

c.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html> 
<head> 
<title>这是c.html</title> 
<meta http-equiv="content-type" content="text/html; charset=gb2312"> 
</head> 
<body> 
<span><strong>这是c.html:<strong></span><span id="span1"></span><br />
<iframe src="d.html" width="500px" height="300px"></iframe>
</body> 
</html>

d.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html> 
<head> 
<title>这是d.html</title> 
<meta http-equiv="content-type" content="text/html; charset=gb2312"> 
<script type="text/javascript">
    function jump(){
        *********
    }
</script>
</head> 
<body> 
<span>这是d.html:</span><span id="span1"></span><br />
<input type='button' onclick='jump();' value='跳转'>
<iframe src="d.html" width="500px" height="300px"></iframe>
</body> 
</html>

打开a.html对应的截图如下:

下面再d.html中写入对应的js代码,看各种跳转是什么样的效果:

    function jump(){
        //经测试:window.location.href与location.href,self.location.href,location.href都是本页面跳转
        //作用一样
        window.location.href="http://www.baidu.com";
        //location.href="http://www.baidu.com";
        //self.location.href="http://www.baidu.com";
        //his.location.href="http://www.baidu.com";
        //location.href="http://www.baidu.com";
    }

再次运行a.html,点击那个"跳转" 按钮,运行结果贴图二如下:

对比图一和图二的变化,你会发现d.html部分已经跳转到了百度的首页,而其它地方没有发生变化。这也就解释了"本页跳转"是什么意思。

好,再来修改d.html里面的js部分为:

    function jump(){
      parent.location.href='http://www.baidu.com';
    }

显示效果如下:

你会发现a.html中嵌套的c.html部分已经跳转到了百度首页。

分析:我点击的是a.html中嵌套的d.html部分的跳转按钮,结果是a.html中嵌套的c.html部分跳转到了百度首页,这就解释了"parent.location.href是上一层页面跳转"的意思。
再次修改d.html里面的js部分为:

    function jump(){
        top.location.href='http://www.baidu.com';
    }

显示效果如下:

分析:我点击的是a.html中嵌套的d.html部分的跳转按钮,结果是a.html中跳转到了百度首页,这就解释了"top.location.href是最外层的页面跳转"的意思。

总结:

看完上面的讲解之后,在来看看下面的定义你就会非常明白了:
"top.location.href"是最外层的页面跳转
"window.location.href"、"location.href"是本页面跳转
"parent.location.href"是上一层页面跳转.

原文地址:https://www.cnblogs.com/DreamDrive/p/4390842.html