這篇文章主要介紹了JS未跨域操作iframe里的DOM 的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下
這里簡單說明兩個(gè)方法,都是未跨域情況下在index.html內(nèi)操作b.html內(nèi)的 DOM。
如:index.html內(nèi)引入iframe,在index內(nèi)如何用JS操作iframe內(nèi)的DOM元素?
先貼下index.html和iframe引入的a.html內(nèi)容。
index->
<div class="d1">
<iframe src="a.html" frameborder="0" name="one" id="iframeId"></iframe>
</div>
a.html
<div id="dd">
<h1>iframe里的元素!</h1>
</div>
法一:
var d=window.frames["one"].window;
d.onload=function(){
console.log(d.document.getElementById("dd"));
};
法二:
JS動態(tài)創(chuàng)建iframe并插入
var ifr = document.createElement('iframe');
ifr.src = 'a.html';
document.body.appendChild(ifr);
ifr.onload = function(){
var doc = ifr.contentDocument || ifr.contentWindow.document;
// 在這里操縱b.html
console.log(doc.getElementById("dd"));
};
兩種的輸出結(jié)果都是
以上所述是小編給大家介紹的JS未跨域操作iframe里的DOM 的相關(guān)知識,希望對大家有所幫助!