2017-01-09 68 views
6

我試圖訪問一個特定的元素(可能更類似於這個)使用iframe對象jQuery但它不起作用。爲什麼我不能使用iframe對象和jQuery來遍歷此元素?

iframeWindow對象是非空但下一個聲明似乎不工作。我在這個答案上看到類似this的東西,但它不起作用。難道我做錯了什麼?

這裏是我的代碼:

RADIO.PHP

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <script type="text/javascript" src="jquery.js"></script> 
    <script> 

     $(document).ready(function(){ 
      setTimeout(function(){ 
      var iframe= document.getElementById("iframe"); 
      var iframeWindow = iframe.contentWindow; 
      var text=iframeWindow.$("div:nth-child(3) .c2").html(); 
      console.log(text); 

      //DOESN'T PRINT "INNER MOST" 

     }, 1000); 

    }); 
    </script> 
</head> 
<body> 
    <div class="c1"> 
    <iframe id="iframe" src="api.php" height="200" width="300"> 
    </iframe> 
    </div> 
</body> 
</html> 

API.PHP

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
</head> 
<script type="text/javascript" src="jquery.js"></script> 
<body id="abody"> 
Hey 
    <div class="c1"></div> 
    <div class="c1"> 
     <p class="c2"></p> 
    </div> 
    <div class="c1"> 
     <p class="c2"> 
     INNER MOST 
     </p> 
    </div> 
</body> 
</html> 

編輯:我已經糾正語法錯誤。

+0

請注意,您的HTML無效。你不能在彼此中嵌套'p'元素,因此DOM結構不匹配你的選擇器 –

+0

我編輯過,請檢查它 – Shanky

+0

'iframeWindow!== inframeWindow'也檢查這一個。 – Jai

回答

2

您應結合使用iframe.contentWindow.document代替iframe.contentWindowfind()text(),它應該工作。試試這個:

$(document).ready(function() { 
    setTimeout(function() { 
    var iframe = document.getElementById("iframe"); 
    var iframeWindow = iframe.contentWindow.document; 
    var text = $(iframeWindow).find(".c1:nth-child(3) .c2").text(); 
    console.log(text); 

    //PRINTS "INNER MOST" 

    }, 1000); 

}); 

MDN文件說:

contentWindow屬性返回IFRAME元素窗口對象。您可以使用此窗口對象訪問iframe的文檔及其內部DOM。該屬性是隻讀的,但其屬性可以像全局Window對象一樣進行操作。

你可以閱讀更多關於iframe元素以及它們是如何工作here

0

這是明顯的看到我和其他所有錯過的錯字,而不是inframeWindow,應該是iframeWindow

而是使用jQuery選擇嘗試:

var text=$(iframeWindow).find("div:nth-child(3) .c2").html(); 

要附加一個jQuery方法,以DOM對象。這不能以這種方式完成。你必須讓它成爲一個jQuery對象來分配一個jQuery方法。

+1

他也應該用'iframeWindow'改變'inframeWindow'。 – Ionut

+0

對不起,但它只是顯示未定義。我無法使用'.text()' – Shanky

0

要爲jQuery中的選擇器指定作用域,請將作用域作爲第二個參數傳遞給jQuery選擇器。

替換:

inframeWindow.$("div:nth-child(3) p .c2") 

$("div:nth-child(3) p .c2", inframeWindow) 

(此外,還有對DOM或jQuery的對象沒有$成員函數)。

+2

獲得文本。他還應該用'iframeWindow'來更改'inframeWindow'。 – Ionut

+0

對不起,但它只是顯示未定義。我無法使用'.text()'獲得文本@ – Shanky

+0

@Richard你有什麼參考嗎?它不會工作。 –

0

試試這個方式希望這將有助於

已更新答案

var $iframe= $("#iframe"); 
var $iframeWindow = $iframe.contents(); 
var text=$iframeWindow.find("div").eq(2).find('p .c2').html(); 
console.log(text); 
+0

對不起,但它只是顯示undefined。我不能使用'.text() – Shanky

+0

看看我已經更新了我的答案 – Curiousdev

相關問題