簡體   English   中英

通過ID賦予null的iframe元素訪問

[英]Iframe element access by Id giving null

的HTML是這樣的

<iframe id="MainFrame">
  <div id="Maintest">This is main text
        <div id ="SecondTest">This is second layer 
            <div id="ThirdTest">This is third layer</div>
        </div> 
  </div>
</iframe>

訪問框架中元素的javascript是這樣的

var iframe = document.getElementById('MainFrame');
    var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
    console.log(iframe);
    var mydiv = innerDoc.getElementById("Maintest");
    console.log(mydiv);
    var seconddiv = innerDoc.getElementById("SecondTest");
    var thirddiv = innerDoc.getElementById("ThirdTest");
    console.log(seconddiv+thirddiv);

mydiv,seconddiv以及thirddiv都給null。我在很多帖子中都看到這是訪問iframe元素的方式。我不知道為什么給iframe。

感謝Swaraj

我認為,您使用iframe的實現不正確。 <iframe>標記內的所有內容都是不支持iframe的瀏覽器所顯示的內容。 我知道只有兩種將內容插入iframe的方法:

<iframe src="/example/content.html">Your browser doesn't support iframes.</iframe>

並使用javascript通過您的innerDoc引用將子節點附加到iframe,例如:

innerDoc.body.appendChild(child_ref);

更新:

請注意,要在iframe中引用的html內容必須位於單獨的文件中,例如my_content.html ,而iframe需要在“ src =“字段中引用該文件,例如: <iframe src="my_content.html">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM