2011-02-18 82 views
2
function test(){ 
alert(this);//alerts oblect 
alert(this.id);//alerts undefined 

} 

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

为什么警报(this.id)警报不确定?这是因为这个返回文件对象?this.id返回什么?

谢谢你

回答

3

你的代码应该是。

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

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

编辑:你也可以使用下面的代码。

<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" /> 
+0

感谢您的回复,我知道这一点。但是有没有一种方法可以知道该函数被触发的对象?在这种情况下,我需要知道该函数是否从text1的按键事件中调用。 – manraj82 2011-02-18 12:06:00

2

this是窗口实例。尝试在你的浏览器:

javascript:alert(this) 

我得到一个[object Window]

0

在全球范围内的情况下(这)是窗口,因为窗口没有财产被称为“ID”的定义。