iframe框架页面中弹出窗口如何使用JS回调?

JavaScript018

iframe框架页面中弹出窗口如何使用JS回调?,第1张

<html>

<head>

<script type="text/javascript">

function parent_click(){

alert("来自父页面")

}

</script>

</head>

<body>

<input type="button" value="调用本页面函数" onclick="parent_click()" />

<input type="button" value="调用子页面函数" onclick='window.frames["childPage"].child_click()' />

<iframe id="childPage" name="childPage" src="inner.html" frameborder="0"></iframe>

</body>

</html>

调用子页方法,用函数传参

第二种方法:

使用MessengerJS

在需要通信的文档中(父窗口和iframe们), 都确保引入MessengerJS

每一个文档(document), 都需要自己的Messenger与其他文档通信. 即每一个window对象都对应着一个, 且仅有一个Messenger对象, 该Messenger对象会负责当前window的所有通信任务. 每个Messenger对象都需要唯一的名字, 这样它们才可以知道跟谁通信.

Js代码

// 父窗口中 - 初始化Messenger对象

var messenger = new Messenger('Parent')

// iframe中 - 初始化Messenger对象

var messenger = new Messenger('iframe1')

// 多个iframe, 使用不同的名字

var messenger = new Messenger('iframe2')

在发送消息前, 确保目标文档已经监听了消息事件.

Js代码

// iframe中 - 监听消息

// 回调函数按照监听的顺序执行

messenger.listen(function(msg){

alert("收到消息: " + msg)

})

父窗口想给iframe发消息, 它怎么知道iframe的存在呢? 添加一个消息对象吧.

Js代码

// 父窗口中 - 添加消息对象, 明确告诉父窗口iframe的window引用与名字

messenger.addTarget(iframe1.contentWindow, 'iframe1')

// 父窗口中 - 可以添加多个消息对象

messenger.addTarget(iframe2.contentWindow, 'iframe2')

一切ready, 发消息吧~ 发送消息有两种方式. (以父窗口向iframe发消息为例)

Js代码

// 父窗口中 - 向单个iframe发消息

messenger.targets['iframe1'].send(msg1)

messenger.targets['iframe2'].send(msg2)

// 父窗口中 - 向所有目标iframe广播消息

messenger.send(msg)

常用两种返回方法:

1.window.showModalDialog(url,args,dialogattrs) 

参数说明: 

url:弹出页面地址 

agrs:主窗口传给对话框的参数,可以是任意类型(数组也可以) 

dialogattrs:弹出窗口的样式参数 

模式对话框用法: 

主窗口:var value =window.showModalDialog('test.jsp',strs,'resizable:yes') 

弹出框中通过window.returnValue设置返回值。

2。window.open: 

【父窗口】 

代码如下: 

<script> 

function show_child() 

var child=window .open("child.html","child","height=200,width=400,status=yes,toolbar=no,menubar=no,location=no") 

/* if(!child.closed) 

if(!window .close()) 

var textValue = frm.txt.value parent.frm0.txt0.value = textValue 

else 

window .close() 

child.close() 

}*/ 

</script> 

<a href="javascript:show_child()">打开子窗口</a> 

<form name=frm0> 

<input type="text" name="txt0" id="txt0"> //注意这里一定要写ID属性不然FF下取不到值 

</form> 

【子窗口】

代码如下: 

<script> 

function choseItem() 

var v="" 

var check_item = document.frm.item 

for(i=0i<check_item.lengthi++) 

if(check_item[i].checked) 

v+=","+check_item[i].value 

document.frm.txt.value=v.replace(/^,{1}/,"") 

function foo() 

window .close() 

window .opener.document.getElementById("txt0").value=document.getElementById("txt").value 

</script> 

<body> 

<form name=frm> 

<input type=checkbox name=item value=1 onclick="choseItem()">a 

<input type=checkbox name=item value=2 onclick="choseItem()">b 

<input type=checkbox name=item value=3 onclick="choseItem()">c 

<input type=checkbox name=item value=4 onclick="choseItem()">d 

<input type=text name="txt" id="txt"> 

</form> 

<input type=button value="关闭" onclick="foo()"> 

</body>