jQuery操作iframe父页面与子页面的元素、函数、变量
第一、在iframe中查找父页面元素的方法:
$(‘#id’, window.parent.document)
第二、在父页面中获取iframe中的元素方法:
$(this).contents().find(“#suggestBox”)
第三、在iframe中调用父页面中定义的方法和变量:
parent.method
parent.value
第四、父页面调用iframe内的JS的方法,无须给iframe加id,只需用Jq选中iframe就行了
$(“#id”).find(“iframe”)[0].contentWindow.func()
iframe里用jquery获取父页面body
iframe.html
<html> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'> </script> <body id='1'> <div>it is a iframe</div> </body> <script> $(document).ready( function() { varc = $(window.parent.document.body) //麻烦的方法: var c = $($(window).eq(0)[0].parent.document).find('body'); ,忘了可以用前面的方法了 alert(c.html()); } ); </script> </html>
content.html
<html> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script> <body id='fa'> <iframe src='iframe.html'width='100'height='100'></iframe> <br> <br> <br> <div id='mydiv'>content iframe</div> </body> <script> functiona() { alert(1); } alert($(document).text()); </script> </html>
在iframe中调用父页面中定义的方法和变量
1.父页面
<!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"> <head runat="server"> <title></title> <script language="javascript"type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script language="javascript"type="text/javascript"> varhello = 'hello'; functiongetHelloWorld() { alert('hello world'); } </script> </head> <body> <form id="form1"runat="server"> <div> <div id="default"style=" width:200px; height:400px; float:left;">default.aspx</div> <iframe id="iframeid"src="IFrame.aspx"style=" width:400px; height:400px; float:left;"></iframe> </div> </form> </body> </html>
2.子页面
<!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"> <head runat="server"> <title></title> <script language="javascript"type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script language="javascript"type="text/javascript"> $(function() { //在iframe中查找父页面元素 alert($('#default', window.parent.document).html()); //在iframe中调用父页面中定义的方法 parent.getHelloWorld(); //在iframe中调用父页面中定义的变量 alert(parent.hello); }); </script> </head> <body> <form id="form1"runat="server"> <div id="iframe"> IFrame.aspx </div> </form> </body> </html>