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.
精彩评论