【问题标题】:Accessing a javascript function in a nested iframe in IE在 IE 的嵌套 iframe 中访问 javascript 函数
【发布时间】:2010-10-29 14:44:42
【问题描述】:

我目前有一个页面结构,它由一个包含 iframe(iframe0) 的页面(Parent) 组成,并且在该 iframe 内我有另一个 iframe(iframe1)。在 iframe1 中,我有一个试图从 Parent 调用的 javascript 函数。在 Firefox/Chrome/Safari 中,我可以使用以下代码调用此函数:

 frames["iframe0"]["iframe1"].functionName();

但是,在 Internet Explorer 中,上述代码不起作用,并返回错误“对象不支持此属性或方法”。我尝试了其他一些方法来访问该方法,它们都返回相同的错误。

 window.frames.iframe0[iframe1].functionName();
 window.iframe0.iframe1.functionName();
 window.frames.iframe0.frames.iframe1.functionName();

我什至尝试调用 iframe0 中的一个函数,该函数调用了 iframe1 中的函数,但它甚至不起作用。

有人知道如何访问嵌套在 2 层深的 iframe 中的 javascript 函数吗?

谢谢。

更新: 在进一步研究问题后,我发现我正在处理的问题与我所问的问题无关。 ylebre 在下面给出的答案回答了我提出的问题,我将在那里标记为答案。我可能会开始另一个更详细地描述我的问题的问题。

【问题讨论】:

    标签: javascript iframe


    【解决方案1】:

    选择 iframe 的一种快速方法是在 dom explorer 中选择它,然后在 js 控制台中运行$0.contentWindow.myFunction()

    【讨论】:

      【解决方案2】:

      我提供了一个使用 3 个 HTML 文件的示例。最外层是 test.html,它有一个包含 iframe1.html 的 iframe。反过来,iframe1.html 包含一个包含 iframe2.html 的 iframe。我希望这是您心目中的那种设置。

      基本上,您可以使用 iframe.contentWindow.myfunc(); 调用 iframe 函数;

      使用 contentWindow.document 您可以访问第二级 iframe。

      示例函数“doit()”调用父级、第一个 iframe 和第二个 iframe 中的函数。

      希望这会有所帮助!

      <!------- test.html -------->
      <html>
      <head>
          <script type="text/javascript">
              function parent_function() {
                  alert('parent');
              }
              function doit() {
                  parent_function();
                  document.getElementsByTagName('iframe')[0].contentWindow.iframe1_function();
                  document.getElementsByTagName('iframe')[0].contentWindow.document.getElementsByTagName('iframe')[0].contentWindow.iframe2_function();
              }
          </script>
      </head>
      <body>
      main
      <a href="javascript:doit();">do it</a>
      <iframe src='iframe1.html'>
      </body>
      </html>
      
      <!------- iframe1.html -------->
      <html>
      <head>
          <script type="text/javascript">
              function iframe1_function() {
                  alert('iframe1');
              }
          </script>
      </head>
      <body>
      frame1
      <iframe src='iframe2.html'>
      </body>
      </html>
      
      <!------- iframe2.html -------->
      <html>
      <head>
          <script type="text/javascript">
              function iframe2_function() {
                  alert('iframe2');
              }
          </script>
      </head>
      <body>
      frame2
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2019-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 1970-01-01
        相关资源
        最近更新 更多