2014-01-31 27 views
0

我怎麼能執行從main.php的button_one()函數?JavaScript - 如何從主頁面執行iframe的功能?

Main.php:

<b>Main page - for the actions</b> 
<div style="position: absolute; right:9%;top:30px;">  
    <input type=button id=b1 /> 
</div> 

<b>Inner page - for the buttons</b> 
<iframe id="layer" src="" ></iframe> 

<script> 
$(document).ready(function() { 
    // by default loaded 
    $('#layer').attr('src', "http://localhost/iframepage.php").show(); 

    // later on click send command to iframe 
    $('#b1').click(function() { 
     // how to execute the iframepage.php button_one() script from here? 
    }); 
}); 
</script> 

iframepage.php:

<b>Welcome</b> 
<script> 
function button_one() { 
alert("button press from main page"); 
} 
</script> 

回答

1

試試這個:

window.frames["layer"].window.button_one() 

但要注意的是,如果iframe SRC是在同一個域中,這隻會工作作爲你執行的腳本(在你的案例localhost)。端口應該與協議一樣。否則,由於安全限制,瀏覽器將阻止此行爲。

+0

我得到這個:'未捕獲的SecurityError:阻止原產框架的 「http:// PBX:80」 訪問的框架與原籍的 「http:// IIIIII:8080」 。協議,域和端口必須匹配。 ' – YumYumYum

+1

正如我在我的答案,域,協議和端口的匹配應該說。如果沒有,則由於安全問題,無法從iframe的父窗口中調用函數。 – antyrat

+0

好的 - 謝謝,我現在明白了。這就是爲什麼不允許。 – YumYumYum

1

使用:

document.getElementById('layer').contentWindow.button_one();