jQuery 如何使用jquery从自身中选择一个iframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1220876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:56:40  来源:igfitidea点击:

how to select an iframe from itself with jquery

jqueryiframe

提问by Rado

I need to select an iframe with an jquery query inside the same iframe. However, I don't want to assign the iframe a unique id and use

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

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

(which i saw somewhere). Is there any relative way to do this (something with $(this) and traversing ??!?)

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

Everything is on the same server, there is no xss.

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

回答by RaYell

If you have only one iFrame on your site it's easy. Just use this selector

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

 $('iframe', parent.document)

If you have more then one it gets more complicated. iFrame document doesn't have a clue in which of the main page iframes it was loaded so there is no easy way of selecting parent iframe with the selector. If you however know the parent id, name, class or even iframe source url you can use that information to modify the selector above to only match iframe that you want. You could also match a iframe you need if you know its index on the main page.

如果你有更多然后一个它会变得更复杂。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); 

回答by karl

To select the second iframe it has to be:

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

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

回答by Zaher Ayrout

you can filter by a specific element (class in the following example) in your iframe

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

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