如果很愚蠢,请道歉。我无法使 this
在 click
事件中工作:
<div onclick='hello()'>
Click here!
</div>
<script>
function hello() {
// I want to do some works with *this* object
alert(this.textContent);
}
</script>
我错过了什么?
最佳答案
您可以使用.call()
The
call()
method calls a function with a given this value
<div onclick='hello.call(this)'></div>
<div onclick='hello.call(this)'>
Click here!
</div>
<script>
function hello() {
console.log(this.textContent);
}
</script>
或者
.bind()
也可以使用。
The
bind()
method creates a new function that, when called, has its this keyword set to the provided value,
<div onclick='hello.bind(this)()'>
Click here!
</div>
<script>
function hello() {
console.log(this.textContent);
}
</script>
关于javascript - onclick 处理程序中的 this 关键字不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42222958/