2014-01-31 58 views
0

拿到冠軍這是我的代碼:與iframe文檔

<div id="main-content"> 
    <script> 
     document.title = document.getElementById("main-content-iframe").contentDocument.title; 
    </script> 
    <iframe name="cstage" src="home.html" width="100%" height="100%" id="main-content-iframe" frameborder="0" onload="document.title=parent.frames['cframe'].document.title;">If you're seeing this message, it means IFrames are not supported; Please enable IFrames or upgrade to a compatible browser that supports IFrames.</iframe> 
</div> 

它不工作,我究竟做錯了什麼?

+0

Javascript控制檯中是否有任何錯誤消息? – Barmar

+1

腳本標記中的js未處於文檔準備就緒調用中,因此它在iframe加載之前執行,因此零件將無法正常工作。 –

+0

你見過這個職位?可能是有用的[使用jquery從javascript獲取iframe頁面標題](http://stackoverflow.com/questions/1570808/get-iframe-page-title-from-javascript-using-jquery) – davewoodhall

回答

4

您需要檢查是否加載了iframe。

<div id="main-content"> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
    <iframe name="cstage" src="home.html" width="100%" height="100%" id="main-content-iframe" frameborder="0" onload="document.title=parent.frames['cframe'].document.title;">If you're seeing this message, it means IFrames are not supported; Please enable IFrames or upgrade to a compatible browser that supports IFrames.</iframe> 
<script> 
    $("iframe").on('load',function() { 
     document.title = document.getElementById("main-content-iframe").contentDocument.title; 
    }); 
</script> 

+5

這很難「無用」,現在呢? –

+0

@ Kalle H.Väravas..給出了一種替代方法....有時它是一些解決方案.. @KenSharp ..投票了..'因爲它認爲它是正確的! –

-1

try代碼也許可以幫助你

HTML code: 
<div id="main-content"> 
    <iframe name="cstage" src="home.html" width="100%" height="100%" id="main-content-iframe" frameborder="0">If you're seeing this message, it means IFrames are not supported; Please enable IFrames or upgrade to a compatible browser that supports IFrames.</iframe> 
</div> 

jQuery code: 
alert($('#main-content-iframe').contents().find("title").text()); 

注意:確保home.html的來自同一個域名爲您的主頁。