How to access the content of an iframe with jQuery

2019-01-01 04:59发布

How can I access the content of an iframe with jQuery? I tried doing this, but it wouldn't work:

iframe content: <div id="myContent"></div>

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

How can I access myContent?


Similar to jquery/javascript: accessing contents of an iframe but the accepted answer is not what I was looking for.

标签: jquery iframe
3条回答
倾城一夜雪
2楼-- · 2019-01-01 05:40

You have to use the contents() method:

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

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

查看更多
刘海飞了
3楼-- · 2019-01-01 05:41

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):

<?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):

$.get(file_url, function(string){
    var html = $.parseHTML(string);
    var contents = $(html).contents();
},'html');
查看更多
永恒的永恒
4楼-- · 2019-01-01 05:42
<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>
查看更多
登录 后发表回答