I'm using an iframe which is added and removed from the page as needed. The iframe contains javascript code which is called from the parent document.
I've found that the iframe 'loses its name', resulting in it no longer being addressable using something like:
window.frames['iframename'].function()
This happens once the function has been called for the first time, and the iframe has been removed and added again. I can always call the function at least once, no matter how many times the iframe is added and removed, and can call it many times if I don't remove the iframe - but as soon as the function has been called, and the 开发者_StackOverflow社区iframe is removed and subsequently added, trying to call the function triggers an error that the function is not defined.
I've been able to get around this by addressing the iframe by it's index, eg:
window.frames[2].function()
But I don't like this kind of 'hardcoding'.
Why is this happening, and what is the best way to call functions in the iframe without resorting to using the iframe's index?
You can correct this problem by just hiding your iframe instead of removing it from page.
every time you want to remove your iframe just set
document.getElementById('iframename').style.display = 'none';
and every time you want to add it you can use
document.getElementById('iframename').style.display = 'block';
this will act as you like.
then you can add your iframe to a javascript variable and call your functions using that variable :
var myFrame = window.frames['iframename'];
myFrame .function()
just consider to add this javascript code after your iframe placement.
精彩评论