【问题标题】:jquery selector from iframe content to object content从 iframe 内容到对象内容的 jquery 选择器
【发布时间】:2014-03-12 08:16:01
【问题描述】:

我需要以下物品:

我有一个html 文档,其中有一个iframe 和一个对象。 iframe 和对象都包含单独的 html 文件。

现在我想点击 iframe 中的链接,这应该会影响要隐藏的对象内的链接。

如何使用jQuery 选择器来选择对象 html 文件中的链接?

结构:

<html file parent>
    <iframe> html site 1 with link to click</iframe>
    <object> html site 2 with links to affect </object>
<html file parent>

提前致谢!

【问题讨论】:

  • 欢迎来到 SO。请take the tour。展示你已经尝试过的,以及没用的。

标签: javascript jquery html object iframe


【解决方案1】:

如果 iframe 的域与您的 .
这是一个 javascript 限制。

【讨论】:

    【解决方案2】:

    为此,您需要控制 iframe 中加载的 url。

    如果它是同一个域,那么你可能可以这样做。

    【讨论】:

      【解决方案3】:

      如果你可以控制 iframe 的 url,试试这个。

      首先,看看window.postMessage。使用它,您可以将事件从 iframe 发送到窗口父目标。在窗口父级中侦听该事件(当 iframe 中的某些内容发生更改时),您将能够使用如下语法访问 object 标记内的任何元素:

      $('object').contents().find('linkSelector')
      

      给你的 iframe 一个 id,比如说myIframe

      <iframe id="myIframe"> html site 1 with link to click</iframe>
      

      获取对 iframe 的引用:

      var myIframe = document.getElementById('myIframe');
      

      从 iframe 发布消息:

      myIframe.contentWindow.postMessage('iframe.clicked', 'http://your-domain.here.com');
      

      iframe 更改处理程序:

      var handleIframeChange = function(e) {
          //
          if(e.origin == 'http://your-domain.here.com') {
              // Get reference to your `object` tag
              var objContent = $('object').contents();
      
              // For instance, let's hide an element with a class of `link-class-here`
              objContent.find('.link-class-here').hide();
          }
      }
      

      在父窗口上监听 iframe 发送的事件:

      window.addEventListener('iframe.clicked', handleIframeChange, false);
      

      现在还没有测试过(过去做过,当时我可以控制 iframe)但它应该可以工作,但正如我所说,只有你可以控制 iframe。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 2017-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多