【发布时间】:2009-08-03 06:21:57
【问题描述】:
我需要在同一个 iframe 中选择一个带有 jquery 查询的 iframe。但是,我不想为 iframe 分配一个唯一的 id 并使用
$('#'+self.name,top.document)
(我在某处看到)。有什么相对的方法可以做到这一点(使用 $(this) 并遍历 ??!?)
一切都在同一个服务器上,没有xss。
【问题讨论】:
我需要在同一个 iframe 中选择一个带有 jquery 查询的 iframe。但是,我不想为 iframe 分配一个唯一的 id 并使用
$('#'+self.name,top.document)
(我在某处看到)。有什么相对的方法可以做到这一点(使用 $(this) 并遍历 ??!?)
一切都在同一个服务器上,没有xss。
【问题讨论】:
如果您的网站上只有一个 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);
【讨论】:
要选择第二个 iframe,它必须是:
second iframe (index is starting from 0)
$('iframe:eq(1)', parent.document);
【讨论】:
您可以在 iframe 中按特定元素(以下示例中的类)进行过滤
$('iframe', parent.document).filter(function (index, element) {
return $(element).contents().find('.specific-element').length;
});
【讨论】: