JavaScript - 如何从主页面执行iframe的功能?

时间:2014-01-31 11:53:53

标签: javascript jquery iframe

如何从main.php执行button_one()函数?

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>

2 个答案:

答案 0 :(得分:1)

试试这个:

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

但请注意,只有当iframe src与您执行的脚本在同一个域中时(在您的情况下为localhost),这才有效。端口应该与协议相同。否则,由于安全限制,浏览器将阻止此行为。

答案 1 :(得分:1)

使用:

document.getElementById('layer').contentWindow.button_one(); 
相关问题