道歉,如果它非常愚蠢。我无法在this
事件中使click
工作:
<div onclick='hello()'>
Click here!
</div>
<script>
function hello() {
// I want to do some works with *this* object
alert(this.textContent);
}
</script>
我错过了什么?
答案 0 :(得分:3)
您可以使用.call()
call()
方法调用具有给定值的函数
<div onclick='hello.call(this)'></div>
<div onclick='hello.call(this)'>
Click here!
</div>
<script>
function hello() {
console.log(this.textContent);
}
</script>
&#13;
或者
.bind()
也可以使用。
bind()
方法创建一个新函数,在调用时,将其this关键字设置为提供的值,
<div onclick='hello.bind(this)()'>
Click here!
</div>
<script>
function hello() {
console.log(this.textContent);
}
</script>
&#13;
答案 1 :(得分:2)
您可以使用addEventListener
代替我实际推荐的内联处理程序。
document.querySelector('div').addEventListener('click', function() {
console.log(this.textContent);
})
<div>
Click here!
</div>
除了call()
/ bind()
之外,您也可以像这样传递this
,只需使用传递的参数。
<div onclick='hello(this)'>
Click here!
</div>
<script>
function hello(el) {
console.log(el.textContent);
}
</script>
处理程序
中this
的值使用时将处理函数附加到元素
addEventListener()
,处理程序中this
的值是a 对元素的引用。它的价值相同 传递给的事件参数的currentTarget
属性 处理程序。如果在元素中指定了事件属性(例如
onclick
) HTML源代码,属性值中的JavaScript代码是 有效地包装在一个处理函数中,该函数绑定了this的值 以与addEventListener()
的使用一致的方式 代码中出现this
表示对该引用的引用 元件。 注意,调用的函数中this
的值 属性值中的代码按standard rules行为。
Src:MDN