[英]Why does addEventListener work with function() but not with a specific function I pass?
Why does addEventListener
work with function()
in the commented code but not with a specific function I pass? 为什么
addEventListener
与注释的代码中的function()
一起使用,而不与我通过的特定函数一起使用?
var button = document.querySelector("button");
// button.addEventListener("click", function(){
// button.classList.toggle("bigyellow");
// });
button.addEventListener("click", toggleMe);
function toggleMe(){
this.classList.toggle("big-yellow");
}
//CSS:
//.bigyellow {
// background-color: #ffff66; /* yellow */
//}
Your this is probably referencing a global object as it's inside a function (that is probably a "window"), so you can try to save the name/caller-id/this of the button before entering into the function to know which button to reference inside it. 您的this可能引用的是全局对象,因为它位于函数内部(可能是“窗口”),因此您可以在进入函数之前尝试保存按钮的名称/主叫ID / this,以了解要使用哪个按钮里面的参考。
For some inside how this works in JavaScript, check: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this 有关它在JavaScript中如何工作的一些内部信息,请检查: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.