iframe页面和原本的页面传值方法实例,可以用于获取父页面和子页面的dom对象的值。
parent.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Home Page For Iframe</title> </head> <body> <h1>This is for iframe</h1> <h2 id="ele">To Get it.</h2> <iframe src="./iframe.html" id="iframe-content" frameborder="1px"> </iframe> </body> </html>
iframe.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Iframe</title> </head> <body> <a href="./parent.html">Home Page</a> <br /> <button onclick="closeiframe();">close iframe</button> <br /> <button onclick="addele();">Add Element To Parent Page</button> <br /> <button onclick="get_parent_ele();">Get Parent Page Ele</button> <script> function closeiframe() { var iframe_content = window.parent.document.getElementById("iframe-content"); console.log(iframe_content); window.parent.document.body.removeChild(iframe_content); } function addele() { var new_title = document.createElement("h1"); console.log(new_title); new_title.innerHTML = "Title For Page"; window.parent.document.body.appendChild(new_title); } function get_parent_ele() { var get_ele = window.parent.document.getElementById("ele"); // alert(get_ele); alert(get_ele.innerHTML); } </script> </body> </html>
在本地的Chrome浏览器无法使用,会出现安全错误。放在服务器上就行了。