如何使用jQuery访问iframe的内容?我试过这样做,但它不起作用:
iframe内容: <div id="myContent"></div>
jQuery的: $("#myiframe").find("#myContent")
我怎样才能访问myContent?
与 jquery/javascript 类似:访问iframe的内容,但接受的答案不是我想要的.
mbi*_*ard 200
你必须使用这个contents()方法:
$("#myiframe").contents().find("#myContent")
Run Code Online (Sandbox Code Playgroud)
资料来源:http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/
and*_*lzo 19
<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>
Run Code Online (Sandbox Code Playgroud)
fir*_*b86 14
如果iframe的源是外部域,浏览器将隐藏iframe内容(同源策略).解决方法是将外部内容保存在文件中,例如(在PHP中):
<?php
$contents = file_get_contents($external_url);
$res = file_put_contents($filename, $contents);
?>
Run Code Online (Sandbox Code Playgroud)
然后,获取新文件内容(字符串)并将其解析为html,例如(在jquery中):
$.get(file_url, function(string){
var html = $.parseHTML(string);
var contents = $(html).contents();
},'html');
Run Code Online (Sandbox Code Playgroud)