javascript - 类型错误 :Cannot read property 'getElementById' frameset

标签 javascript frame getelementbyid frameset

我有一个简单的代码,每次有新版本时都会刷新主页,但它只适用于 Internet Explorer。在其他浏览器中我收到以下错误:

Uncaught TypeError: Cannot read property 'getElementById' of undefined line 24

这是我的代码:

    <html>

    <script type="text/javascript">
     var num=0;
     var currVersion;
     var started=false;

     function startLoad() {
     var url= "version_telemark.html?"+ (++num);
        window.version.navigate(url);
     }

     function endLoad() {
       if (started) {
         var newVersion = version.document.getElementById("version").value;
         if (newVersion != currVersion) {
           currVersion=newVersion;
           var url  = "telemark.html?"+ (++num);
             window.pane.navigate(url);
         }
       }
     }
     function start() {
        currVersion = version.document.getElementById("version").value;
       started=true;
       setInterval("startLoad()", 200);
     }
    </script>

  <frameset    onload="start()"  cols="40%,100%">
    <frame id="version"   src="version_telemark.html"/>
    <frame id="pane" src="telemark.html" />
  </frameset>

</html>

在我的其他文件中,我只有我想要编辑的文件:

<input id="version" name="version" type="textbox" value="700">

我的另一个具有设计的文件只有表格,但我们不需要在其中添加任何内容。

最佳答案

有两件事:

  1. 您的代码依赖于浏览器为具有 id 的元素创建的自动全局,通过使用 version 作为全局变量而无需声明或初始化它。也许由于某种原因,自动全局不适用于 IE 以外的浏览器。无论如何,我不喜欢依赖它们,因为太容易隐藏它们,所以我建议通过在脚本顶部附近添加以下内容来有意获取该元素:

    var version = document.getElementById("version");
    

    但你对这个问题的评论表明这不是这个,而是下面的#2:

  2. 您的 currVersion = version.document.getElementById("version").value 中可能需要 vesrion.contentDocument 而不是 version.document ; 和类似的行;也许是 JavaScript 的强大得令人好奇的 || 运算符:

    var versionDoc = version.document || version.contentDocument;
    // ...and then
    currVersion = versionDoc.getElementById("version").value;
    // ...and so on
    
<小时/>

旁注:为了让您自己以及在您之后维护代码的人保持理智,我还建议 version frame 使用不同的 id 和其中的版本 输入

关于javascript - 类型错误 :Cannot read property 'getElementById' frameset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27446752/

相关文章:

javascript - 从 <object> 节点获取 SVG 根元素及其子元素以导出具有动态内容的 SVG

javascript - 八月错误的 Date.parse javascript

javascript - 检查一个元素是否存在于对象数组中

javascript - 如何阻止 Safari 在我的 &lt;input type ="search"> 字段中放置放大镜图像?

iphone - 以编程方式创建一个 View ,并将框架设置为 super View 的框架?

javascript - 元素无法分配给变量

Javascript 客户端 - 从网页上的现有图像创建新图像

iphone - 如何找出屏幕方向,纵向还是横向?

wpf - 在 WPF Frame 控件中关闭导航页面声音

javascript - 在 switch 语句案例中使用 getElementByID.innerHTML?