如何使用 jQuery 访问 iframe 的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1796619/
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 access the content of an iframe with jQuery?
提问by mbillard
How can I access the content of an iframe with jQuery? I tried doing this, but it wouldn't work:
如何使用 jQuery 访问 iframe 的内容?我尝试这样做,但它不起作用:
iframe content:<div id="myContent"></div>
iframe 内容:<div id="myContent"></div>
jQuery:$("#myiframe").find("#myContent")
jQuery:$("#myiframe").find("#myContent")
How can I access myContent
?
我如何访问myContent
?
Similar tojquery/javascript: accessing contents of an iframebut the accepted answer is not what I was looking for.
类似于jquery/javascript: accessing content of an iframe但接受的答案不是我想要的。
回答by mbillard
You have to use the contents()
method:
您必须使用以下contents()
方法:
$("#myiframe").contents().find("#myContent")
Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/
来源:http: //simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/
API Doc: https://api.jquery.com/contents/
API 文档:https: //api.jquery.com/contents/
回答by andres descalzo
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(function() {
//here you have the control over the body of the iframe document
var iBody = $("#iView").contents().find("body");
//here you have the control over any element (#myContent)
var myContent = iBody.find("#myContent");
});
</script>
</head>
<body>
<iframe src="mifile.html" id="iView" style="width:200px;height:70px;border:dotted 1px red" frameborder="0"></iframe>
</body>
</html>
回答by fireb86
If iframe's source is an external domain, browsers will hide the iframe contents (Same Origin Policy). A workaround is saving the external contents in a file, for example (in PHP):
如果 iframe 的来源是外部域,浏览器将隐藏 iframe 内容(同源策略)。解决方法是将外部内容保存在文件中,例如(在 PHP 中):
<?php
$contents = file_get_contents($external_url);
$res = file_put_contents($filename, $contents);
?>
then, get the new file content (string) and parse it to html, for example (in jquery):
然后,获取新的文件内容(字符串)并将其解析为 html,例如(在 jquery 中):
$.get(file_url, function(string){
var html = $.parseHTML(string);
var contents = $(html).contents();
},'html');