簡體   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