這裡簡單說明兩個方法,都是未跨域情況下在index.html內操作b.html內的 DOM。
如:index.html內引入iframe,在index內如何用JS操作iframe內的DOM元素?
先貼下index.html和iframe引入的a.html內容。
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動態創建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"));
};
兩種的輸出結果都是

以上所述是小編給大家介紹的JS未跨域操作iframe裡的DOM 的相關知識,希望對大家有所幫助!