【问题标题】:how to select an iframe from itself with jquery如何使用jquery从自身中选择一个iframe
【发布时间】:2009-08-03 06:21:57
【问题描述】:

我需要在同一个 iframe 中选择一个带有 jquery 查询的 iframe。但是,我不想为 iframe 分配一个唯一的 id 并使用

$('#'+self.name,top.document)

(我在某处看到)。有什么相对的方法可以做到这一点(使用 $(this) 并遍历 ??!?)

一切都在同一个服务器上,没有xss。

【问题讨论】:

    标签: jquery iframe


    【解决方案1】:

    如果您的网站上只有一个 iFrame,这很容易。只需使用此选择器

     $('iframe', parent.document)
    

    如果你有更多那么一个它会变得更复杂。 iFrame 文档不知道它是在哪个主页 iframe 中加载的,因此没有简单的方法可以使用选择器选择父 iframe。但是,如果您知道父 ID、名称、类甚至 iframe 源 url,您可以使用该信息来修改上面的选择器以仅匹配您想要的 iframe。如果您知道主页上的索引,也可以匹配所需的 iframe。

     // iframe with MyClass class
     $('iframe.MyClass', parent.document);
    
     // iframe with MyId id
     $('iframe#MyId', parent.document);
     // even better since id is unique
     $('#MyId', parent.document);
    
     // iframe with myname name
     $('iframe[name=myname]', parent.document);
    
     // iframe with specific src
     $('iframe[src=/path/to/iframe/source]', parent.document);
    
     // second iframe (index is starting from 0)
     $('iframe:eq(1)', parent.document); 
    

    【讨论】:

    • 感谢您的详细回复。我以为我忽略了某些东西,但现在我发现没有简单的方法解决它。
    【解决方案2】:

    要选择第二个 iframe,它必须是:

    second iframe (index is starting from 0)
    $('iframe:eq(1)', parent.document);
    

    【讨论】:

      【解决方案3】:

      您可以在 iframe 中按特定元素(以下示例中的类)进行过滤

      $('iframe', parent.document).filter(function (index, element) {
          return $(element).contents().find('.specific-element').length;
      });
      

      【讨论】:

        猜你喜欢
        • 2011-09-13
        • 1970-01-01
        • 1970-01-01
        • 2013-03-13
        • 2012-10-07
        • 2016-06-26
        • 1970-01-01
        • 2015-05-17
        • 1970-01-01
        相关资源
        最近更新 更多