javascript - 从 iFrame 中的按钮关闭(对话框)iFrame

标签 javascript html css

我有两个文件,名为 main_page.htmldialog_box.html(见下面的代码)。 我希望我的 handleCloseDialogBu​​tton() 能够“关闭对话框”,换句话说,使用 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');

在您的 handleCloseDialogBu​​tton 函数中使用它并将其显示设置为无:

function handleCloseDialogButton()
{
window.parent.document.getElementById('myDialogBox').style.display="none";
}

注意:这在 Chrome 的文件模式下不起作用。你必须将你的页面放在网络服务器上,然后它也可以在 Chrome 浏览器中运行。

关于javascript - 从 iFrame 中的按钮关闭(对话框)iFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27958984/

相关文章:

javascript - 自动排列多个图像以适合整个网页

javascript - 如何在 JavaScript 中匹配以输入结尾结尾的最小模式?

javascript - JQuery 不读取动态创建的元素属性

javascript - 为什么我的密码总是只正确加密第一个字母而不是第二个、第三个字母等

javascript - 限制外部 CSS 对本地 React 组件或 HTML 元素的影响

javascript - 使用左右导航按钮选择不同的 div 框架

javascript - 将参数发送到本地 HTML 文件

php - 使用 CakePHP 跨 2 个 div 拆分表单

javascript - 动画宽度导致内部元素从未知高度跳起来

python - django 找不到静态/css 文件错误 404