簡體   English   中英

我無法從iframe中調用父函數

[英]i'm unable to call the parent function from within iframe

我已經看到了與此有關的其他帖子,但是由於某種原因,以下方法無效。

onclick="parent.testing();" 

現在查看全文。 我有一個index.html,其中包含所有JS文件。 同樣在索引中,我有一個空的'div'標簽。 使用jQuery,我將page1.html文件附加到空的“ div”。 所以索引有點像這樣:

<html>
<head>
<script files>
<script>
ready { function testing(){do stuff;} }
</script>
</head>
<body>
<div><iframe src="page1.html" (added via jQuery)></div>
</body>
</html>

現在在page1.html文件中,當我單擊鏈接時,我正在嘗試調用一個函數。 但我收到以下錯誤:

Uncaught TypeError: Cannot call method 'testing' of undefined 

我也嘗試了以下方法,但是它們沒有起作用:

onclick="window.testing();"
onclick="window.frames[0].testing();" 

您的父頁面腳本不是有效的JavaScript,但假設ready { ... }

<script>
ready { function testing(){do stuff;} }
</script>

...是一種簡化形式,它代表了一個文檔就緒處理程序,您正在將testing()聲明為該就緒處理程序中的本地函數,因此只能從該就緒處理程序中對其進行訪問。 您需要在父頁面中將testing()全局:

<script>
$(document).ready({ /* your on ready stuff here */ });

function testing(){ /* do stuff; */ }
</script>

...然后您應該可以使用parent.testing()從iframe調用它。

如果我理解您的問題,那么您的問題就是您的函數沒有被調用,對吧? 因此,也許一個解決方案是將其放在您的“ page1.html”中

<script type="text/javascript" src="your_js_file"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM