2009-11-25 95 views
85

如何使用jQuery訪問iframe的內容?我試着這樣做,但它不會工作:如何使用jQuery訪問iframe的內容?

iframe中的內容:<div id="myContent"></div>

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

如何我可以訪問myContent


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

+0

我剛剛發現Firefox控制檯中的內置$變量看起來不像完整的jQuery。 (我意識到我沒有jQuery變量,然後發現我沒有加載jQuery的源代碼)。 –

回答

160

您必須使用contents()方法:

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

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

+3

給我錯誤:錯誤:權限被拒絕訪問屬性'ownerDocument' –

+22

ime:它可能會給你錯誤,因爲以下原因:1)iframe不屬於同一個域。 2)您正在嘗試在Iframe加載事件之前閱讀它。 – iMatoria

+0

有沒有辦法在嘗試訪問它並獲取錯誤之前驗證iframe內容是否來自同一個域? – Kamafeather

15
<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> 
12

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