簡體   English   中英

如何從另一個 iFrame 清除 iFrame 的內容

[英]How to clear the contents of an iFrame from another iFrame

我有一個wrapperPage.html<iframe class="header"<iframe class="pageBody" header有一個鏈接<a class="clearLink" ,點擊它時應該清除pageBody的內容。

到目前為止,上述想法的以下實現不起作用。 請幫我解決這個問題。

請注意headerpageBody分別從不同的包含文件加載。

包裝頁面.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 中)以對其進行管理。

例如 :

  • 在 pageBody.html 中編寫一個與自定義事件關聯的函數。
  • header.html iFrame 中的單擊函數獲取窗口引用。
  • 搜索已分配自定義事件的目標元素。
  • 觸發事件

我希望它能幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM