jQuery 如何在 iframe 中找到一个 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4602738/
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
How to find a div inside of an iframe
提问by rajaishbt
I am trying to use jquery to find a div inside an iframe. Is there a better way than the one I'm using below?
我正在尝试使用 jquery 在 iframe 中查找 div。有没有比我在下面使用的方法更好的方法?
$('#Iframe').contents().find('#MyDiv')
function atmslidein(){
$("#customer").ready(function(){
if($('#customer').attr('src')=='ATM.html')
{
$('#customer').contents().find('.atm_page').css('margin-left', '270px');
$('#customer').contents().find('.tele').css('display', 'none');
}
})
}
I've tried almost a week to make this work:
我已经尝试了将近一个星期来完成这项工作:
$('#Iframe').contents().find('#MyDiv')
That is why I tried another way to access the iframe's div.
这就是为什么我尝试了另一种方法来访问 iframe 的 div。
Anyway I found something that the iframe document should have and only then the above function works properly:
无论如何,我发现了 iframe 文档应该有的东西,只有这样上面的功能才能正常工作:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
My problem is solved, thanks. But could someone explain why this is necessary?
我的问题解决了,谢谢。但是有人可以解释为什么这是必要的吗?
回答by moribvndvs
I don't think the jQuery
can access the contentWindow/Document's content in that way. In the past, I've had to do this:
我认为jQuery
不能以这种方式访问 contentWindow/Document 的内容。过去,我不得不这样做:
$('#iframe').each(function() {
$('#MyDiv', this.contentWindow.document||this.contentDocument);
});
** Note that this.contentWindow||this.contentDocument
is required to work correctly across IE and most other browsers. Once you get the content window, you need to select the document. Then you can use jQuery to manipulate or traverse the DOM, but only if the iframe's source is in the same domain.
** 请注意,这this.contentWindow||this.contentDocument
是在 IE 和大多数其他浏览器中正常工作所必需的。获得内容窗口后,您需要选择文档。然后就可以使用 jQuery 来操作或遍历 DOM,但前提是 iframe 的源在同一个域中。
** Updated to fix error where we don't specify the document after we get the contentWindow/Document.
** 更新以修复我们在获取 contentWindow/Document 后未指定文档的错误。
回答by Luis
This will only work if the Iframe source is in the same domain as your page, if not the browser wont allow it for security reasons
这仅在 Iframe 源与您的页面位于同一域中时才有效,否则浏览器出于安全原因将不允许它
回答by Lex
Use selector context:
使用选择器上下文:
var frame = $('#frame_id');
var div = $('#mydiv', frame);