简体   繁体   English

this.id返回什么?

[英]what does this.id return?

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 ? 为什么alert(this.id)警报未定义 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. this是窗口实例。 Try it in your browser: 在浏览器中尝试:

javascript:alert(this)

I get an [object Window] 我得到一个[object Window]

在全局范围内,上下文是窗口,因为窗口没有未定义的称为“ id”的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM