简体   繁体   中英

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

i've seen the other posts in regard to this, but the following method is not working for some reason.

onclick="parent.testing();" 

now for the full story. i have an index.html that houses all the JS files. also within the index, i have an empty 'div' tag. with jQuery, i'm appending a page1.html file to the empty 'div'. so the index kinda looks like this:

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

now in the page1.html file, i'm trying to call a function when a link is clicked. but i'm receiving the following error:

Uncaught TypeError: Cannot call method 'testing' of undefined 

i've also tried the following but they didn't work:

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

Your parent page script isn't valid JavaScript, but assuming ready { ... } :

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

...is a simplification supposed to represent a document ready handler you are declaring testing() as a local function within that ready handler so it can only be accessed from within that ready handler. You need to make testing() global in the parent page:

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

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

...and then you should be able to call it from the iframe using parent.testing() .

If I understand your question, your problem it's your function is not called, right? So maybe a solution is to put this in your "page1.html"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM