2013-08-30 92 views
2

我在iFrame中使用jQuery時遇到了問題。在iFrame中使用jQuery不起作用

這裏是我的測試設置:

的index.html:

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<title>Untitled Document</title> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
<script type="text/javascript"> 

$(document).ready(function(){ 
    $("#A").contents().find('#B').addClass('Z');  
}); 

</script> 
</head> 
<body> 

<iframe id="A" src="test.html" style="width:700px; height: 1000px;" frameborder="0"></iframe> 

</body> 
</html> 

的test.html:

<html> 
<head> 
<title>test</title> 
</head> 
<body> 
<div id="B">testcontent</div> 
</body> 
</html> 

通常,當加載頁面時,在源,應該添加「Z」作爲一個類,但它不會。有沒有人有一個想法可能是什麼問題?這兩個文件都在同一個(本地)文件夾中。

+0

這可能是加載的iframe的內容之前執行的功能。嘗試做:$('iframe')。ready(function(){});取而代之,看看它的工作 –

+0

。在iframe上沒有任何用處。 .load另一方面可能會有所幫助。 –

回答

3

您必須使用HTTP方案(http://https://)從網絡服務器運行它。

使用文件方案(file://)可防止在某些瀏覽器中進行此類交叉幀訪問。

7

試試這個

$("iframe").load(function(e){ 
    $(this).contents().find('#B').addClass('Z'); 
}); 
+0

這不起作用 – user63457

+2

更正:一旦在網絡服務器上,這確實有用! – user63457