如何使用jQuery访问iframe的内容?我尝试过以下代码,但没有成功:
iframe内容: <div id="myContent"></div>
jQuery: $("#myiframe").find("#myContent")
我该如何访问myContent
?
类似于 jquery/javascript: accessing contents of an iframe 但是已接受的答案不符合我的要求。
如何使用jQuery访问iframe的内容?我尝试过以下代码,但没有成功:
iframe内容: <div id="myContent"></div>
jQuery: $("#myiframe").find("#myContent")
我该如何访问myContent
?
类似于 jquery/javascript: accessing contents of an iframe 但是已接受的答案不符合我的要求。
contents()
方法:$("#myiframe").contents().find("#myContent")
<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>
如果iframe的源是外部域名,浏览器将隐藏iframe内容(同源策略)。 一种解决方法是将外部内容保存在文件中,例如(在PHP中):
<?php
$contents = file_get_contents($external_url);
$res = file_put_contents($filename, $contents);
?>
然后,获取新文件内容(字符串)并将其解析为HTML,例如(使用jQuery):
$.get(file_url, function(string){
var html = $.parseHTML(string);
var contents = $(html).contents();
},'html');