sal*_*e55 58 javascript iframe
我iframe在父页面中调用JavaScript函数时遇到问题.这是我的两页:
mainPage.html
<html>
<head>
    <title>MainPage</title>
    <script type="text/javascript">
        function Reset() 
        {
            if (document.all.resultFrame)
                alert("resultFrame found");
            else
                alert("resultFrame NOT found");
            if (typeof (document.all.resultFrame.Reset) == "function")
                document.all.resultFrame.Reset();
            else
                alert("resultFrame.Reset NOT found");
        }
    </script>
</head>
<body>
    MainPage<br>
    <input type="button" onclick="Reset()" value="Reset"><br><br>
    <iframe height="100" id="resultFrame" src="resultFrame.html"></iframe>
</body>
</html>
resultFrame.html
<html>
<head>
    <title>ResultPage</title>
    <script type="text/javascript">
        function Reset() 
        {
            alert("reset (in resultframe)");
        }
    </script>
</head>
<body>
    ResultPage
</body>
</html>
(我知道document.all不推荐这个,但这个页面只能在内部用IE查看,我不认为这是问题)
当我按下重置按钮时,我得到"找到resultFrame"和"找不到resultFrame.Reset".它似乎有一个框架的引用,但不能调用框架上的功能,为什么会这样?
Jon*_*and 110
使用:
document.getElementById("resultFrame").contentWindow.Reset();
访问iframe中的重置功能
document.getElementById("resultFrame")
将在您的代码中获取iframe,并将在iframe中contentWindow获取窗口对象.拥有子窗口后,您可以在该上下文中引用javascript.
另请参阅此处 特别是bobince的答案.
不要从文档中获取帧,而是尝试从窗口对象中获取帧.
在上面的例子中改变了这个:
if (typeof (document.all.resultFrame.Reset) == "function")
    document.all.resultFrame.Reset();
else
    alert("resultFrame.Reset NOT found");
至
if (typeof (window.frames[0].Reset) == "function")
    window.frames[0].Reset();
else
    alert("resultFrame.Reset NOT found");
问题是iframe中的javascript范围不是通过iframe的DOM元素公开的.只有窗口对象包含帧的javascript范围信息.
为了更加健壮:
function getIframeWindow(iframe_object) {
  var doc;
  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }
  if (iframe_object.window) {
    return iframe_object.window;
  } 
  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 
  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }
  if (doc && doc.defaultView) {
   return doc.defaultView;
  }
  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }
  return undefined;
}
和
...
var el = document.getElementById('targetFrame');
var frame_win = getIframeWindow(el);
if (frame_win) {
  frame_win.reset();
  ...
}
...
| 归档时间: | 
 | 
| 查看次数: | 146782 次 | 
| 最近记录: |