在处理 iframe 交互时,我们常常需要读取子页面里的元素值。下面通过一个登录页的示例,演示如何获取同源 iframe 中 body 下某个标签的值。
首先是主页面 test.html,点击按钮后读取 iframe 内用户名的输入值:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
$("#show").click(function (){
var iframeObj = $(window.frames["iframe_name"].document);
alert(iframeObj.find("#un").val());
});
});
</script>
</head>
<body>
<input type="button" id="show" value="show" />
<iframe id="iframe_id" name="iframe_name" src="https://localhost/test/login.html"></iframe>
</body>
</html>
接着是被嵌入的 login.html,里面包含一个用户名输入框:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录页面</title> </head> <body> <form method="POST" action="#"> 用户名:<input id="un" type="text" name="username" value="123d" /> 密 码:<input type="text" name="password"/> <input type="submit" value="提交"> </form> </body> </html>
核心代码是 $(window.frames["iframe_name"].document),它先拿到 iframe 的 document 对象,再用 find() 定位到目标元素并取值。需要特别强调的是:这种跨文档访问必须在同源前提下才能生效,否则会触发浏览器的同源安全策略而无法读取。