最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - what does this.id return? - Stack Overflow

programmeradmin0浏览0评论
function test(){
alert(this);//alerts 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

function test(){
alert(this);//alerts 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

Share Improve this question asked Feb 18, 2011 at 12:02 manraj82manraj82 6,34525 gold badges58 silver badges85 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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)

  1. 暂无评论