浏览器主页、iframe、子窗口的互相操作

来源:互联网 发布:手机淘宝怎么取消订单 编辑:程序博客网 时间:2024/06/05 03:46

主页操作iframe

var ifs = document.getElementById('iframeID').contentWindow.document;  \\获取到iframe的document对象document.getElementById('iframeID').contentWindow.jsMethod(); \\调用iframe的JS方法ifs.getElementById('elementID').onclick(function(){alert('function binding in main page!');});  \\在主页中为iframe绑定主页的方法

子iframe操作主页
var pp = parent.document; \\获取主页的documentparent.jsMethod(); \\调用主页JS方法pp.getElementById('elementID').onclick(function(){alert('function binding in main page!');});  \\在iframe中为主页绑定iframe中的方法

主窗口操作子窗口
var nw = window.open("about:blank"); var nd = nw.document; \\获取子窗口的documentnw.jsMethod(); \\调用子窗口JS方法

子窗口中操作主窗口
var od = opener.document;  \\获取主窗口的documentopener.showJS();  \\调用主窗口的js

样例代码:

<html><head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script><script>var nw;var injectHtml = '<hr><div><p>inject success</p>\<div>iframe test<input type="button" value="test parent DOM" onclick="parent.document.getElementById(\'showtext\').innerHTML=\'parent element changed!\'" >\<input type="button" value="test parent JS" onclick="parent.showJS();" ></div>\<div>new window test<input type="button" value="test parent DOM" onclick="opener.document.getElementById(\'showtext\').innerHTML=\'parent element changed!\'" >\<input type="button" value="test parent JS" onclick="opener.showJS();" ></div>\<div>method binding<input type="button" value="open parent new window" id="bindingmethod" >\<input type="button" value="show iframe" id="binding2"></div>\</div>';$(document).ready(function(){});function injectWithIframe(html){if (nw) {nw.close()};var iframe = '<iframe src="about:blank" frameborder="0" name="FirebugUI" id="FirebugUI" style="border: 0px; visibility: visible; z-index: 2147483647; position: fixed; width: 100%; left: 0px; bottom: 0px; height: 241px; display: block;"></iframe>';$("#iframediv").append(iframe);var ifs = document.getElementById('FirebugUI').contentWindow.document;$(ifs.body).html(html);$('#bindingmethod', ifs.body).click(this.opennewwithhtml);}function opennewwithhtml(){openInNewWindow(injectHtml);}function openInNewWindow(html){$('#iframediv').empty();nw = window.open("about:blank");$(nw.document.body).html(html);$('#binding2', nw.document.body).click(this.showIframe);}function showIframe(){injectWithIframe(injectHtml)}function showJS(){$('#showtext').text('parent JS called!');}</script></head><body><div><input type="button" value="inject iframe" onclick="javascript:injectWithIframe(injectHtml)" ><input type="button" value="inject new window" onclick="javascript:openInNewWindow(injectHtml)" ></div><div id="showtext"></div><div id="iframediv"></div></body></html>

0 0
原创粉丝点击