一:提出问题
使用js的同学一定知道js的location.href的作用是什么,但是在js中关于location.href的用法究竟有哪几种,究竟有哪些区别,估计很多人都不知道了。
二:常见的几种形式
目前在开发中经常要用到的几种形式有:
1
2
3
4
5
6
|
self.location.href;
window.location.href;
this
.location.href;
location.href;
parent.location.href;
top.location.href;
|
经常见到的大概有以上几种形式。
三:代码部分
那么,这几种形式的跳转究竟有什么区别呢?
直接讲定义,你肯定不会理解透彻,下面我来贴四个html代码,用实际的例子讲解。
a.html:
1
2
3
4
5
|
<
form
id
=
"form1"
action
=
""
>
<
div
><
strong
>这是a.html页面<
strong
>
<
iframe
src
=
"b.html"
width
=
"500px"
height
=
"300px"
></
iframe
> </
strong
></
strong
></
div
>
</
form
>
<
pre
>
|
1
2
|
<
span
>这是b.html</
span
><
span
id
=
"span1"
></
span
><
br
/>
<
iframe
src
=
"c.html"
width
=
"500px"
height
=
"300px"
></
iframe
>
|
1
2
|
<
span
><
strong
>这是c.html:<
strong
></
span
><
span
id
=
"span1"
></
span
><
br
/>
<
iframe
src
=
"d.html"
width
=
"500px"
height
=
"300px"
></
iframe
>
|
1
2
3
|
<
span
>这是d.html:</
span
><
span
id
=
"span1"
></
span
><
br
/>
<
input
type
=
'button'
onclick
=
'jump();'
value
=
'跳转'
>
<
iframe
src
=
"d.html"
width
=
"500px"
height
=
"300px"
></
iframe
>
|
观察代码,我们可以看出:
a.html里面嵌着b.html;
b.html里面嵌着c.html;
c.html里面嵌着d.html
运行a.html,贴图一如下:
四:测试几种用法
下面来测试上述几种写法.
在d.html里面head部分写js:
1
2
3
4
5
6
7
8
9
10
|
<strong>
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";
//this.location.href="http://www.baidu.com";
//location.href="http://www.baidu.com";
} </strong>
|
对比图一和图二的变化,你会发现d.html部分已经跳转到了百度的首页,而其它地方没有发生变化。这也就解释了"本页跳转"是什么意思。
好,再来修改d.html里面的js部分为:
1
2
3
4
|
function
jump()
{
parent.location.href=
'http://www.baidu.com'
;
}
|
![](http://static.oschina.net/uploads/space/2013/0328/224324_Oohf_224980.png)
对比图一和图三,你会发现a.html中嵌套的c.html部分已经跳转到了百度首页。
分析:我点击的是a.html中嵌套的d.html部分的跳转按钮,结果是a.html中嵌套的c.html部分跳转到了百度首页,这就解释了"parent.location.href是上一层页面跳转"的意思。
再次修改d.html里面的js部分为:
1
2
3
4
|
function
jump()
{
top.location.href=
'http://www.baidu.com'
;
}
|
你会发现,a.html已经跳转到了百度首页。
分析:我点击的是a.html中嵌套的d.html部分的跳转按钮,结果是a.html中跳转到了百度首页,这就解释了"top.location.href是最外层的页面跳转"的意思。
五:总结
看完上面的讲解之后,在来看看下面的定义你就会非常明白了:
"top.location.href"是最外层的页面跳转
"window.location.href"、"location.href"是本页面跳转
"parent.location.href"是上一层页面跳转.
这样解释一切都很明朗了。
<iframe src="demo_iframe.htm" name="iframe_a"></iframe>
<p><a href="http://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>
其实这个也是蛮好理解的,就是说在原有设置展示界面中重新显示超链接的内容