本文實例講解在 JavaScript 中呼叫 iframe 框架頁面裡函式的方法。這個呼叫方式其實非常簡單,掌握之後便能實現 iframe 之間的傳值或修改值。以下分享具體實作。
存取 iframe 裡面的函式:
document.getElementById('commentIframe').contentWindow.hasLogined();
其中 commentIframe 為 iframe 的 id,且要在 window.onload 裡面執行。
例子如下:
1.html:
<a href="#" onclick="window.frames['frame1'].MyNext()">aa</a>
<iframe id="frame1" src="2.html"></iframe>
2.html 頁面:
<script language="javascript" type="text/javascript">
function MyNext() { alert(1); }
</script>
若要呼叫 2.htm 中的 JS 函式,可以這樣寫:
self.frames['a'].funtionname(param)
在 1.htm 中呼叫 2.htm 中的 JS 函式:iframe2.showInfo();
以下用更完整的例子說明。假設有兩個頁面 index.html 與 inner.html,其中 index.html 有一個 iframe,其 src 指向 inner.html。我們要實現:在 index.html 中呼叫 inner.html 上的一個 JS 方法;以及在 inner.html 中呼叫 index.html 上的一個 JS 方法。
index.html:
<html>
<head>
<script type="text/javascript">
function ff() {
alert(">>this is index's js function index.html");
}
</script>
</head>
<body>
<div style="background: lightblue;">
This is index page.
<input type="button" value="run index's function" onclick="ff();" />
<input type="button" value="run inner page's function" onclick='window.frames["childPage"].sonff();' />
</div>
<iframe id="childPage" name="childPage" src="inner.html" width="100%" frameborder="0"></iframe>
</body>
</html>
inner.html:
<html>
<head>
<script type="text/javascript">
function sonff() {
alert(">>this is inner page's js function");
}
</script>
</head>
<body>
<div style="background: lightgreen;">
This is inner page.
<input type="button" value="run index's function" onclick='parent.window.ff();' />
<input type="button" value="run inner page's function" onclick="sonff();" />
</div>
</body>
</html>
關鍵在於:父頁面用 window.frames["frameName"].函式() 呼叫子頁面的函式,子頁面則用 parent.window.函式() 呼叫父頁面的函式。希望本文對大家基於 JavaScript 的 Web 程式設計有所幫助。