开发者

what does this.id return?

function test(){
alert(this);//a开发者_运维百科lerts oblect
alert(this.id);//alerts undefined

}

<input type="text" onKeyPress="test();" id="text1">

why does alert(this.id) alert undefined? Is this because this returns the document object?

Thank You


Your code should be.

function test(objRef){
  alert(objRef);//alerts oblect
  alert(objRef.id);//alerts undefined
}

<input type="text" onKeyPress="test(this);" id="txtNum" />

EDIT: You may use following code too.

<script type="text/javascript">
        window.onload = function() {
            var txtnum = document.getElementById("txtNum");
            txtnum.onkeypress = function() {
                alert(this);
                alert(this.id);
            };
        };
 </script>

 <input type="text" id="txtNum" />


this is the window instance. Try it in your browser:

javascript:alert(this)

I get an [object Window]


In global scope the context (this) is windows, since window have no property called "id" its undefined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜