簡體   English   中英

iframe“ src”屬性問題

[英]The iframe “src” attribute issue

我正在嘗試document.write在iframe中。 我問了一個問題( 單擊iframe外部的按鈕時是否可以在iframe中寫東西? ),並得到了一些答案,但是存在一個問題:當我向iframe標簽添加“ src”屬性時,代碼停止工作,它不會在iframe中寫入任何內容。

下面的代碼不起作用:

<button onclick="test()">Click to write in iframe</button>

<iframe id='ifr' src = "myDocument.html"></iframe>
<script>

function test(){
    var iframe = document.getElementById("ifr"); 
    //contentDocument because IE8 doesn't support contentWindow
    (iframe.contentDocument || iframe.contentWindow.document).write("hello iframe");   
}

</script>

但是,如果刪除“ src”屬性,它將起作用。

關於為什么會發生的任何想法?

可以使用src屬性而不是document.write:

var htmlString="<p>Hello iframe</p>";
var ifr = document.getElementById('ifr');
ifr.src="javascript:'"+htmlString+"'";

htmlString可以是html或只是文本。

上面的技術等效於html5中的srcdoc屬性。

暫無
暫無

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

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