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>
<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>



// 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(); 这一句 可以将它做成循环一定次数。这样就可以保证多层次结构的页面都可以同时响应事件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值