如何使用jQuery访问iframe的内容?

时间:2009-11-25 12:31:09

标签: jquery iframe

如何使用jQuery访问iframe的内容?我试过这样做,但它不起作用:

iframe内容: <div id="myContent"></div>

jQuery: $("#myiframe").find("#myContent")

如何访问myContent


  

jquery/javascript: accessing contents of an iframe类似,但接受的答案并非我所寻找的。

3 个答案:

答案 0 :(得分:189)

您必须使用contents()方法:

$("#myiframe").contents().find("#myContent")

来源:http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

答案 1 :(得分: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>

答案 2 :(得分:14)

如果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');