[英]How to clear the contents of an iFrame from another iFrame
我有一個wrapperPage.html
與<iframe class="header"
和<iframe class="pageBody"
。 在header
有一個鏈接<a class="clearLink"
,點擊它時應該清除pageBody
的內容。
到目前為止,上述想法的以下實現不起作用。 請幫我解決這個問題。
請注意, header
和pageBody
分別從不同的包含文件加載。
包裝頁面.html
<div class=non-floater>
<iframe class="header" src="header.html"></iframe>
<iframe class="pageBody" src="pageBody.html" />
</div>
標頭.html:
<script type="text/javascript">
$(document).ready(function() {
$(".clearLink").on("click", function() {
$('.pageBody').contents().find("body").html('');
});
});
</script>
<a class="clearLink" href="#">Navigation Button</a>
pageBody.html :
<div class="panel-body">This is the body</div>
嘗試使用頻道消息
wrapperPage.html
<body>
<div class=non-floater>
<iframe class="header" src="header.html"></iframe>
<iframe class="pageBody" src="pageBody.html" />
</div>
<script>
var channel = new MessageChannel();
var header = $(".header")[0].contentWindow;
var pageBody = $(".pageBody")[0].contentWindow;
header.onload = function() {
this.postMessage("","*", [channel.port2])
};
channel.port1.onmessage = function(e) {
if (e.data === "clicked") {
$(pageBody.document.body).html("")
}
}
</script>
</body>
header.html
<body>
<a class="clearLink" href="#">Navigation Button</a>
<script>
var port;
onmessage = function(e) {
port = e.ports[0];
}
$(".clearLink").on("click", function(e) {
port.postMessage("clicked");
});
</script>
</body>
您可以從 iFrame 獲取主窗口的引用,如下所示: Window.Parent 引用
然后,您可以分配一個事件來捕獲主窗口中的觸發器或函數(或僅在其他 iFrame 中)以對其進行管理。
例如 :
header.html
iFrame 中的單擊函數獲取窗口引用。我希望它能幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.