如題:在工作中遇到問題。主頁面發出事件,該頁面中嵌入的iframe的頁面也要響應該事件操作。例如主頁面登錄後,該頁面加載的iframe頁也要根據登錄情況作出不同的顯示。
主頁面
- <!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>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>主頁</title>
- <script src="base.js" language="javascript"></script>
- <script>
- function callsub(){
- CliBase.getInstance().dispatchEvent( new Event('testcall','success'));
- }
- function testhandler(e){
- alert("來自主頁面的:"+e.args)
- }
- CliBase.getInstance().addEventListener('testcall',testhandler)
- </script>
- </head>
- <body>
- 主頁面
- <a href="javascript:callsub();">呼叫子頁面</a>
- <iframe id="aa" src="sub.html" height="500" width="100%" ></iframe>
- </body>
- </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">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>subpage</title>
- <script src="base.js" language="javascript"></script>
- <script>
- window.onload = function(){
- if(window.parent!=null){
- CliBase.getInstance().addEventListener('testcall',testhandler);
- }
- }
- function testhandler(e){
- document.getElementById("output").innerHTML="來自子頁面的"+e.args;
- }
- </script>
- </head>
- <body>
- ifamre中的頁面
- <div id="output" align="ouput"></div>
- </body>
- </html>
他們共同都需要加載的js文件
- // JavaScript Document
- function Event(type,args)
- {this.type = type;
- this.args = args;}
- /**
- * @author andypan
- * 操作基類
- */
- var CliBase = (function() {
- var _eventList = new Array();
- var uniqueInstance; // Private attribute that holds the single instance.
- // Return the constructor.
- return function() {
- // implements Publication
- this.getEventList = function() {return _eventList;}
- }})();
- CliBase.prototype.addEventListener = function(EventType,handler){
- this.getEventList().push([EventType,handler]);
- }
- CliBase.prototype.removeEventListener = function(EventType,handler){
- for(var i=0;i<this.getEventList().length;i++){
- if((EventType==this.getEventList()[i][0])&&(handler==this.getEventList()[i][1])){
- this.getEventList().splice(i,1);
- }
- }
- }
- CliBase.prototype.dispatchEvent = function(Event){
- for(var i=0;i<this.getEventList().length;i++){
- if(Event.type==this.getEventList()[i][0]){
- this.getEventList()[i][1](Event);
- }
- }
- }
- CliBase.getInstance = function(){
- if(this.instance ==null) this.instance = new CliBase();
- if(window.parent!=window){
- //子頁面被實例化後,替換現有實例
- this.instance = window.parent.CliBase.getInstance();
- }
- return this.instance;
- }
我覺得關鍵就是 this.instance = window.parent.CliBase.getInstance(); 這一句 可以將它做成循環一定次數。