关键问题是,onclick的时候如何取得p呢?有高手麻烦告诉我一下。

解决方案 »

  1.   

    Test.prototype._foo =function(){
        if( this.targetElement == undefined ){
            alert( "why?" );
        }else{
            alert( "never come." );
        }
    }当前的window[align=center]====  ====
    [/align]
      

  2.   

    你new Test()之后,并没有变量持有这个"实例"的引用,所以是不可能在拿回来这个"实例"了。
    你可以让targetElement持有这个"实例",这样就可以了。微软的ajax就是这个思想。
      

  3.   

    <html>
    <head>
    <script language="javascript">
    function Test(sID){
        this.targetElement = document.getElementById( sID );
        this.targetElement.onclick = this._foo;   //给控件的onclick这样来添加处理时,此时的this是控件本身
        this.p1 = sID;
    }
    Test.prototype._foo = function(){
    //此时this为test1这个text控件
    alert(this.type)//输出为text
        if( this.targetElement == undefined ){
            alert( "why?" );
        }else{
            alert( "never come." );
        }
    }
    Test.prototype._foo2 = function(){
        if( this.p1 == undefined ){
            alert( "never come." );
        }else{
            alert( this.p1 );
        }
    }
    </script>
    </head>
    <body>
    <form>
        <input type="text" id="test1" />
        <script language="javascript">
            var p = new Test('test1');
            p._foo2();
        </script>
    </form>
    </body>
    </html>
    <html>
    <head>
    <script language="javascript">
        function Init(){
            var p = document.getElementById( 'test' );        
            p.attachEvent( "onchange", _Foo ); //使用attachEvent时,则在_Foo中this为window对象
        }
        function _Foo(){
            alert( this.value );
        }
    </script>
    </head>
    <body>
    <form>
    <select id="test">
        <option value="1">1</option>
        <option value="2" selected>2</option>
        <option value="3">3</option>
    </select>
    <script language="javascript">Init();</script>
    </form>
    </body>
    </html>
      

  4.   

     this.targetElement.onclick = this._foo;  你执行的控件的onclick事件 那么this就是控件本身。。
      

  5.   

    其实this是一个很好很强大的东西。
      

  6.   


    <html>
    <head>
    <script language="javascript">
    function Test(sID){
        this.targetElement = document.getElementById( sID );
        this.targetElement.onclick = this._foo();    
        this.p1 = sID;
    }
    Test.prototype._foo = function(){
         var obj = this;//用一个变量保存这个实例
         return function(){
             if( obj.targetElement == undefined )
                alert( "why?" );
             else
                alert( "never come." );
        }
    }
    Test.prototype._foo2 = function(){
        if( this.p1 == undefined ){
            alert( "never come." );
        }else{
            alert( this.p1 );
        }
    }
    </script>
    </head>
    <body>
    <form>
        <input type="text" id="test1" />
        <script language="javascript">
            var p = new Test('test1');
            p._foo2();
        </script>
    </form>
    </body>
    </html>