繁体   English   中英

为什么addEventListener只能与function()一起使用,而不能与我通过的特定函数一起使用?

[英]Why does addEventListener work with function() 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 */
//}

您的this可能引用的是全局对象,因为它位于函数内部(可能是“窗口”),因此您可以在进入函数之前尝试保存按钮的名称/主叫ID / this,以了解要使用哪个按钮里面的参考。

有关它在JavaScript中如何工作的一些内部信息,请检查: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM