Jquery 調用iframe中的js


在工作中要在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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM