简体   繁体   English

如何从另一个 iFrame 清除 iFrame 的内容

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

I have a wrapperPage.html with an <iframe class="header" and <iframe class="pageBody" .我有一个wrapperPage.html<iframe class="header"<iframe class="pageBody" In header there is a link, <a class="clearLink" , which when clicked should clear the contents of pageBody .header有一个链接<a class="clearLink" ,点击它时应该清除pageBody的内容。

So far the following implementation of the above idea doesn't work.到目前为止,上述想法的以下实现不起作用。 Please help me resolve this.请帮我解决这个问题。

Please NOTE that, header and pageBody are each loaded from different included files.请注意headerpageBody分别从不同的包含文件加载。

wrapperPage.html包装页面.html

<div class=non-floater>
    <iframe class="header" src="header.html"></iframe>
    <iframe class="pageBody" src="pageBody.html" /> 
</div>

header.html :标头.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 : pageBody.html :

<div class="panel-body">This is the body</div>

Try using Channel messaging尝试使用频道消息

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>

You can get the reference of the main window from an iFrame as follow: Window.Parent reference您可以从 iFrame 获取主窗口的引用,如下所示: Window.Parent 引用

Then, you can assign an event to catch a trigger or a function in the main window (or only in the other iFrame) to manage it.然后,您可以分配一个事件来捕获主窗口中的触发器或函数(或仅在其他 iFrame 中)以对其进行管理。

For example :例如 :

  • Write a function in pageBody.html associated to a custom event.在 pageBody.html 中编写一个与自定义事件关联的函数。
  • Get window reference from your click function in your header.html iFrame.header.html iFrame 中的单击函数获取窗口引用。
  • Search target element which has your custom event assigned.搜索已分配自定义事件的目标元素。
  • Fire the event触发事件

I would hope it help you.我希望它能帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM