Javascript onclick处理程序中的this关键字无效
如果它很愚蠢,我会道歉。我无法使Javascript onclick处理程序中的this关键字无效,javascript,html,Javascript,Html,如果它很愚蠢,我会道歉。我无法使此在单击事件中工作: <div onclick='hello()'> Click here! </div> <script> function hello() { // I want to do some works with *this* object alert(this.textContent); } </script> 点击这里! 函数h
此
在单击事件中工作:
<div onclick='hello()'>
Click here!
</div>
<script>
function hello() {
// I want to do some works with *this* object
alert(this.textContent);
}
</script>
点击这里!
函数hello(){
//我想用这个物体做一些工作
警报(this.textContent);
}
我缺少什么?您可以使用
call()
方法调用具有给定此值的函数
点击这里!
函数hello(){
console.log(this.textContent);
}
您可以使用
call()
方法调用具有给定此值的函数
点击这里!
函数hello(){
console.log(this.textContent);
}
您可以使用addEventListener
而不是内联处理程序,我实际上建议您使用内联处理程序
document.querySelector('div').addEventListener('click',function(){
console.log(this.textContent);
})
点击这里!
您可以使用addEventListener
而不是内联处理程序,我实际上建议您使用内联处理程序
document.querySelector('div').addEventListener('click',function(){
console.log(this.textContent);
})
点击这里!
onclick='hello()'
missing()
@Satpal No.我想处理这个“我想在hello函数中访问这个对象。”-你希望this
有什么值?onclick='hello()'
missing
@Satpal No.我想处理这个问题“我想在hello函数中访问此对象。”-您希望此具有什么值?使用.call()
很有趣……这样做有什么好处吗?@zer00ne,什么好处?它只设置了这个
上下文非常感谢。这是一个解决办法。但是我能不能请你帮助我理解为什么直接寻址函数名不起作用?@Hans,我没有上面的精确答案。根据我的理解,它就是这样设计的请记住,这些是@Satpal在我的回答中使用.call()发布的为什么/如何
很有趣……这样做有什么好处吗?@zer00ne,什么好处?它只设置了这个
上下文非常感谢。这是一个解决办法。但是我能不能请你帮助我理解为什么直接寻址函数名不起作用?@Hans,我没有上面的精确答案。根据我的理解,它就是这样设计的记住这些是@Satpal在我的answer@Hans更新了我的答案why@Hans用“为什么”更新了我的答案
<div onclick='hello.call(this)'></div>