我有两个文件,名为 main_page.html
和 dialog_box.html
(见下面的代码)。
我希望我的 handleCloseDialogButton()
能够“关闭对话框”,换句话说,使用 theFrame.style.display
重新加载 main_page.html
重置为“无”。
我怎样才能做到这一点 ?我应该使用 window.open("main_page.html")
还是 window.location.href="main_page.html"
还是别的?
注意:我不想使用 Javascript 的 alert()
函数,因为它的功能不足以满足我的需要。
main_page.html 的内容:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<script>
function handleDialogButton()
{
var theFrame=document.getElementById("myDialogBox");
theFrame.style.display="block";
theFrame;
}
</script>
</head>
<body>
<div id="myDiv"> <h2> Hello world. This is the main page.</h2></div>
<iframe id="myDialogBox" src="./dialog_box.html" style="display:none"> </iframe>
<input type="button" id="dbbutton" name="dbbutton" value="Open Dialog Box"
onClick="javascript:handleDialogButton();" />
</body>
</html>
dialog_box.html 的内容:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<script>
function handleCloseDialogButton()
{
}
</script>
</head>
<body>
<div id="myDiv"> <h2> Hello world. I am the dialog box.</h2></div>
<input type="button" id="cbbutton" name="cbbutton" value="Close Dialog Box"
onClick="javascript:handleCloseDialogButton();" />
</body>
</html>
最佳答案
您可以使用 window.parent 从 iframe 访问父元素。 参见 window.parent了解详情。
使用 window.parent 可以调用父 js 函数,也可以访问父元素。在您的案例中访问父元素应该类似于:window.parent.document.getElementById('myDialogBox');
在您的 handleCloseDialogButton 函数中使用它并将其显示设置为无:
function handleCloseDialogButton()
{
window.parent.document.getElementById('myDialogBox').style.display="none";
}
注意:这在 Chrome 的文件模式下不起作用。你必须将你的页面放在网络服务器上,然后它也可以在 Chrome 浏览器中运行。
关于javascript - 从 iFrame 中的按钮关闭(对话框)iFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27958984/