頁面中嵌入 iframe 後,往往需要從父頁面讀取 iframe 內部元素的值。由於不同瀏覽器的寫法有差異,本文整理出相容 IE 與 Firefox 的完整做法。
IE 的做法是:
document.frames['myFrame'].document.getElementById('test').value;
Firefox 的做法是:
document.getElementById('myFrame').contentWindow.document.getElementById('test').value;
可以透過判斷 document.frames 是否存在,來自動切換兩種模式:
function getValue(){
var tmp = '';
if(document.frames){
tmp += 'ie哥說:';
tmp += document.frames['myFrame'].document.getElementById('test').value;
}else{
tmp = document.getElementById('myFrame').contentWindow.document.getElementById('test').value;
}
alert(tmp);
}
父頁面 a.html 中放入 iframe 與觸發按鈕,子頁面 b.html 則準備一個 id 為 test 的輸入框,按下按鈕即可讀出 iframe 內的值。