2016-12-15 142 views
0

我的DOM如下。從父標記中獲取元素ID

<html><head>...</head><body><script>...</script> 
<iframe id="frame"> 
    #document 
    <html>...</html> <!-- 2 --> 
</iframe> 
</body> 
</html> 

我在iframe(即html 2)中綁定了部分內容。在html_2部分,我打電話document.ready得到idiframe使用getElementById,但我得到null。如何獲得iframe的id和其他屬性值?

+0

第一:你爲什麼要使用iframe? – madalinivascu

+0

http://stackoverflow.com/questions/5864505/javascript-get-iframe-id-within-loaded-page –

+0

使用getElementById獲取iframe的ID?您在getElementById中使用什麼ID來獲取iframe,其ID是「frame」? –

回答

0

我這樣做如下,

$("#iframe", parent.document).attr("id"); 

順便說一句,感謝所有誰回答和價值的意見幫助了我。

0

$("iframe").each(function() { 
 
    alert($(this).attr("id")); 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<html> 
 

 
<head>...</head> 
 

 
<body> 
 
    <script> 
 
    ... 
 
    </script> 
 
    <iframe id="frame"> 
 

 
    </iframe> 
 
    <iframe id="frame1"> 
 

 
    </iframe> 
 
    <iframe id="frame2"> 
 

 
    </iframe> 
 
</body> 
 

 
</html>

  1. 使用.attr("id")
  2. 對於多個iframe中使用.each()到艾弗遍歷所有的iframe
  3. 使用此功能可以獲取當前的iframe
+0

我已經添加了所有需要的jquery。並警報給我空。我已經嘗試過了。 – DhavalR

+0

那麼如果你能提供一個演示或片段來展示你現在擁有的東西,那就更好了。 – guradio

+0

有一個html頁面,我指向一個javascript。在這個腳本中,我調用了一個創建iframe的函數(使用src = controller方法獲取部分內容)。在這部分,我指向另一個js,在這個js中,有document.ready,我想要iframe的屬性值。實際上在Iframe中,作爲父母,部分綁定。 – DhavalR

0

嘗試使用這樣的:

document.getElementById("frame").contentWindow.document.getElementById("div1") 
+0

什麼是'div1'。?它在iframe或html_2(在我的情況下)...? – DhavalR

+0

@DhavalR它將是'iframe' HTML中的一個元素 – philantrovert