【问题标题】:Accessing HTML elements inside frames from parent document从父文档访问框架内的 HTML 元素
【发布时间】:2013-08-13 18:28:59
【问题描述】:

如何从父文档访问框架中包含的 HTML 元素?
我试过 window.frames、contentWindow 和 parent.frames,但我得到了各种各样的错误。

这是父 HTML 文件的代码:

<html>
    <head>
        <title>Parent HTML file</title>
        <script type="text/javascript">
            alert(window.frames["frame1"].window.getElementsByTagName("input")[0].value);
            alert(document.getElementsByName("frame1").contentWindow);
            alert(parent.frames[0]document.getElementsByTagName("input")[0].value);
        </script>
    </head>
        <frameset cols="50%,50%">
            <frame src="frame1.html" name="frame1">
            <frame src="frame2.html" name="frame2">
                <noframes>
                    <body>
                        <p>Text</p>
                    </body>
                </noframes>
        </frameset>
</html>

【问题讨论】:

  • 那么window.frame1 呢?
  • Firefox:window.frame1 未定义
  • 框架已从 HTML5 中删除。如果这是一个新项目,您应该找到不同的方式。
  • 这不是一个严肃的项目,它只是一个练习。我可以看到框架,但无法使用 javascript 正确访问它们。

标签: javascript html css frames


【解决方案1】:

frames 集合或任何inputs 在您尝试引用它们时不存在。你可以试试这个:

window.onload = function () {
    alert(window.frames["frame1"].document.getElementsByTagName("input")[0].value;
}

注意,frames collection 包含 window 对象而不是 frame/iframe 元素。

【讨论】:

  • 它适用于 getElementsByTagName,但不适用于 getElementsByName。
  • 嗯...getElementsByName() 还返回一个NodeList,您需要使用[0](或其他索引)...为什么不给id input,你想显示哪个值,使用document.getElementById()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多