js/jquery獲取iframe子頁面中元素的方法:
一、使用window.frames["iframe的ID"]獲取元素
window.onload = function() { var oIframe = window.frames["oIframe"].document.getElementById("getFrame"); console.log(oIframe); }
注意:此處一定要加上window.onload或者DOMContentLoaded,也就是DOM加載或者頁面加載完成后。
二、使用window.name獲取元素
var oIDframe = window.oIframe.document.getElementById("getFrame"); console.log(oIDframe);
oIframe是iframe的name屬性值,這種獲取方法不必寫在window.onload或者DOMContentLoaded中,請自行測試。
三、使用getElementById獲取元素
var oIdFrame = document.getElementById("oIframe").contentWindow.document.getElementById("getFrame"); console.log(oIdFrame);
使用document.getElementById獲取本頁面的iframe元素后,再獲取iframe子頁面的元素。這種獲取方法不必寫在window.onload或者DOMContentLoaded中
四、使用jquery獲取
var ojIframe = $("#oIframe").contents().find("#getFrame").html(); console.log(ojIframe);
js/jquery iframe子頁面獲取父頁面元素的方法:
一、使用js
var fatherEle = window.parent.document.getElementById("title"); console.log(fatherEle);
二、使用jq
var fatherEleJq = $("#title",parent.document); console.log(fatherEleJq);
父頁面:
<div id="title"> index包含iframe子頁面 </div> <div id="parent"> <iframe name="oIframe" id="oIframe" src="iframe.html" frameborder="0" width="1000" height="562"></iframe> </div>
iframe.html子頁面:
<div id="getFrame">iframe</div>
