JS 实现跨页事件响应
如题:在工作中遇到问题。主页面发出事件,该页面中嵌入的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><iframeid="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>
// JavaScript Documentfunction 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();}CliBase.prototype.removeEventListener = function(EventType,handler){ for(var i=0;i<this.getEventList().length;i++){ if((EventType==this.getEventList())&&(handler==this.getEventList())){ this.getEventList().splice(i,1); } }}CliBase.prototype.dispatchEvent = function(Event){ for(var i=0;i<this.getEventList().length;i++){ if(Event.type==this.getEventList()){ this.getEventList()(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(); 这一句 可以将它做成循环一定次数。这样就可以保证多层次结构的页面都可以同时响应事件了。
页:
[1]