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

}

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


为什么alert(this.id)警报未定义?这是因为这返回了文档对象吗?

谢谢

最佳答案

您的代码应该是。

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

关于javascript - this.id返回什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5041044/

10-12 00:06
查看更多