在工作中要在html中嵌入iframe 並且調用其中的js方法。
網上找的demo都是 html中一個點擊事件的方法中調用到iframe中的js.
點擊觸發后,此時iframe早已被渲染完成,所以這么干是可行的。
現在我遇到的情況是在沒有任何操作的前提下,html加載后就調用iframe中的js.
以下利用到 Jquery的load()方法,待iframe加載完成后,調用其js.
parent.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>ifram測試</title> 6 <script src="https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script> 7 </head> 8 <body> 9 10 <iframe id="iframe1" src="child.html" height="500px" width="500px"> 11 </iframe> 12 <script> 13 $(document).ready(function(){ 14 $("#iframe1").load(function(){ 15 $("#iframe1")[0].contentWindow.sayHello('hello world'); 16 }); 17 18 }); 19 </script> 20 </body> 21 </html>
child.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 </head> 6 <body> 7 8 <p>這是iframe頁面 </p> 9 <script> 10 function sayHello(text){ 11 console.info(text); 12 } 13 </script> 14 </body> 15 </html>