[英]The this keyword in onclick handler is not working
Apologizes if it is very dumb. 抱歉,如果很傻的话。 I cannot make
this
work in a click
event: 我无法在
click
事件中使this
工作正常进行:
<div onclick='hello()'>
Click here!
</div>
<script>
function hello() {
// I want to do some works with *this* object
alert(this.textContent);
}
</script>
What am I missing? 我想念什么?
You can use .call()
您可以使用
.call()
The
call()
method calls a function with a given this valuecall()
方法调用具有给定值的函数
<div onclick='hello.call(this)'></div>
<div onclick='hello.call(this)'> Click here! </div> <script> function hello() { console.log(this.textContent); } </script>
Or 要么
.bind()
can also be used. .bind()
也可以使用。
The
bind()
method creates a new function that, when called, has its this keyword set to the provided value,bind()
方法创建一个新函数,该函数在被调用时将其this关键字设置为提供的值,
<div onclick='hello.bind(this)()'> Click here! </div> <script> function hello() { console.log(this.textContent); } </script>
You can use addEventListener
instead of the inline handler, which I actually would recommend. 您可以使用
addEventListener
代替我实际上建议的内联处理程序。
document.querySelector('div').addEventListener('click', function() { console.log(this.textContent); })
<div> Click here! </div>
In addition to call()
/ bind()
, you can pass the this
like this as well, and simply use the passed parameter. 除了
call()
/ bind()
,您还可以像这样传递this
,并且只需使用传递的参数即可。
<div onclick='hello(this)'> Click here! </div> <script> function hello(el) { console.log(el.textContent); } </script>
The value of
this
within the handler该值
this
处理程序中When attaching a handler function to an element using
addEventListener()
, the value ofthis
inside the handler is a reference to the element.使用
addEventListener()
将处理程序函数附加到元素时,该值在处理程序内部的值是this
元素的引用。 It is the same as the value of thecurrentTarget
property of the event argument that is passed to the handler.它与传递给处理程序的事件参数的
currentTarget
属性的值相同。If an event attribute (eg,
onclick
) is specified on an element in the HTML source, the JavaScript code in the attribute value is effectively wrapped in a handler function that binds the value of this in a manner consistent with the use ofaddEventListener()
an occurrence ofthis
within the code represents a reference to the element.如果在HTML源代码中的元素上指定了事件属性(例如
onclick
),则属性值中的JavaScript代码将有效地包装在处理程序函数中,该函数以与addEventListener()
一致的方式绑定该值在代码中出现this
表示对该元素的引用。 Note that the value ofthis
inside a function called by the code in the attribute value behaves as per standard rules .请注意 ,在属性值的代码所调用的函数内部的
this
值的行为符合标准规则 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.