this.name單擊按鈕元素時,我需要在控制臺中顯示。
我可以替換內部clicked()并設定console.log(myBtn.name),但我希望此方法適用于任何物件。
有沒有辦法做到這一點?當我單擊時,我得到一個空字串。
謝謝!
class Button {
constructor(name, id) {
this.name = name;
this.ref = document.getElementById(id);
this.init();
}
init() {
this.ref.addEventListener("click", this.clicked);
}
clicked() {
console.log(this.name);
}
}
let myBtn = new Button('My button', "test");
<button id="test">Click me</button>
uj5u.com熱心網友回復:
你快到了
您的代碼中的問題是這在回呼中意味著什么
按下按鈕時是this按鈕,除非您另有說明
class Button {
constructor(name, id) {
this.name = name;
this.ref = document.getElementById(id);
this.init();
}
init() {
this.ref.addEventListener("click", this.clicked.bind(this));
}
clicked() {
console.log(this.name);
}
}
let myBtn = new Button('My button', "test");
<button id="test">Click me</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466848.html
標籤:javascript html javascript 对象 这
