先丢两个示例页面上来,test1.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>test</title>
</head>
<body>
<a href="test2.html" target="iframe">test</a>
<iframe src="test2.html" frameborder="0" name="iframe" id="iframe"></iframe>
</body>
</html>
test2.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>test2</title>
</head>
<body>
<button id="button">变化name</button>
<script>
var button = document.getElementById("button");
button.onclick = function(){
name = 123;
}
</script>
</body>
</html>
今天后端人员遇到这么一个问题,在子页面中改变name值以后,父页面中的a标签的target将会失效,不会再指定的iframe中加载页面。
出现该问题的原因是window对象中有name属性,a标签打开页面的时候会去查找iframe中页面的window.name从而确定在哪个iframe中打开指定页面。在子页面中改变了name值,导致无法找到iframe,所以会在新的页面中加载。要避免该问题只要注意变量在使用前先进行声明即可。
test2.html(修改后)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>test2</title>
</head>
<body>
<button id="button">变化name</button>
<script>
var button = document.getElementById("button");
button.onclick = function(){
var name = 123;
}
</script>
</body>
</html>
