<script type="text/javascript">
        function getObjectRef(name) {
            if (document.getElementById) return document.getElementById(name);
            else if (document.all) return document.all[name];
            else return null;
        }
        function Object() {
            document.write("<div id='obj' style='width:10px;height:10px;background-color:red;'></div>");
            this.obj = "obj";
            this.showText = function () {
                getObjectRef(this.obj).innerHTML = "3123123";
            }
            getObjectRef(this.obj).onmouseover = this.showText;
        }
        var obj1=new Object();
 </script>
这段代码执行的时候,当我把鼠标放到红方块上的时候,提示“getObjectRef(this.obj).innerHTML = "3123123";
”对象为空。为什么?不明白。希望哪位大侠帮忙解决一下我改怎么改?

解决方案 »

  1.   

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
     <HEAD>
      <TITLE> New Document </TITLE>
    <script type="text/javascript">
      function getObjectRef(name) {
      if (document.getElementById) return document.getElementById(name);
      else if (document.all) return document.all[name];
      else return null;
      }
      function Object() {
      document.write("<div id='obj' style='width:10px;height:10px;background-color:red;'></div>");
      this.obj = "obj";
      var self = this;
      this.showText = function () {
    getObjectRef(self.obj).innerHTML = "3123123";
      }
      this.initEvent = function(){
    getObjectRef(self.obj).onmouseover = self.showText;
      }
     // getObjectRef(this.obj).onmouseover = this.showText;
      }
      var obj1=new Object(); function init(){
    obj1.initEvent()
    } </script>
     </HEAD>
     <BODY onload="init()"> 
     </BODY>
    </HTML> getObjectRef(this.obj).onmouseover = this.showText;
    主要是这句话,因为你new对象是在head里面,那个时候文档还没有全部加载完,也就是说body里面还没有那个div,所以会找不到这个对象,因此需要在onload里面初始化事件