请参阅此codepen
或下面的代码段
单击按钮时如何让按钮登录到控制台?我正在尝试学习如何在JavaScript中使用this
。感谢
const button = document.getElementById("leet");
function LeetSpeaker (elem) {
return {
listenClick () {
const self = this
elem.addEventListener('click', function () {
self.speakLeet()
})
},
speakLeet() { console.log(`1337 15 4W350M3`) }
}
}
button {
background-color: #b666d2;
border: none;
width: 100px;
height: 30px;
font-size: 1em;
border-radius: 10px;
font-family: Verdana;
}
button:hover {
background-color: rebeccapurple;
}
<button id="leet" onclick="LeetSpeaker(button)">Click</button>
答案 0 :(得分:1)
您的代码中的问题不是this
。摆脱内联javascript,在你的js代码中执行LeetSpeaker(button).listenClick(),它可以工作。要做得更好,请使用箭头功能,然后只需this.speakLeet()
const button = document.getElementById("leet");
LeetSpeaker(button).listenClick();
function LeetSpeaker(elem) {
return {
listenClick() {
const self = this
elem.addEventListener('click', function() {
self.speakLeet()
})
},
speakLeet() {
console.log(`1337 15 4W350M3`)
}
}
}
button {
background-color: #b666d2;
border: none;
width: 100px;
height: 30px;
font-size: 1em;
border-radius: 10px;
font-family: Verdana;
}
button:hover {
background-color: rebeccapurple;
}
<button id="leet">Click</button>
或更好,带箭头功能
const button = document.getElementById("leet");
LeetSpeaker(button).listenClick();
function LeetSpeaker(elem) {
return {
listenClick() {
elem.addEventListener('click', () => {
this.speakLeet()
})
},
speakLeet() {
console.log(`1337 15 4W350M3`)
}
}
}
button {
background-color: #b666d2;
border: none;
width: 100px;
height: 30px;
font-size: 1em;
border-radius: 10px;
font-family: Verdana;
}
button:hover {
background-color: rebeccapurple;
}
<button id="leet">Click</button>