< button id = "elem" > Click me < /button>
<
script >
class Menu {
handleEvent(event) {
// mousedown -> onMousedown
let method = 'on' + event.type[0].toUpperCase() + event.type.slice(1);
this[method](event);
}
onMousedown() {
elem.innerHTML = "Mouse button pressed";
}
onMouseup() {
elem.innerHTML += "...and released.";
}
}
let menu = new Menu();
elem.addEventListener('mousedown', menu);
elem.addEventListener('mouseup', menu); <
/script>
有人能帮我理解这段代码是怎么回事吗?谢谢你。
handleEvent(event) {
// mousedown -> onMousedown
let method = 'on' + event.type[0].toUpperCase() + event.type.slice(1);
this[method](event);
}
event.type[0].toUpperCase() -- this will return first character of your event name in upper case.(e.g. for submit event, it will return `S` )
event.type.slice(1) -- this will return you all characters of event name except first character. (e.g. for submit event , it will return `ubmit`)
那么您将上面的on
连接起来。
在函数的最后一行之后,你调用从上面的字符串生成的派生函数,例如onSubmit
。
在您的情况下,看起来您正在捕获mousedown
事件&然后将该事件转换为onMousedown()
字符串&调用onMousedown()
方法