我想知道如何 "美化""简化 "下面的代码。
function handleKeyDown (e) {
if (e.key === 'Enter') {
e.preventDefault()
myCustomEvent(e)
return
}
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault()
e.key === 'ArrowDown'
? document &&
document.activeElement &&
document.activeElement.nextElementSibling &&
document.activeElement.nextElementSibling.focus()
: document &&
document.activeElement &&
document.activeElement.previousElementSibling &&
document.activeElement.previousElementSibling.focus()
}
}
我觉得太啰嗦了 It seems too verbose to me.
是不是我做错了什么?
我怎样才能写得更好?
你可以使用可选的链锁 document?.activeElement?.nextElementSibling?.focus?.()
function isActive(){
return document && document.activeElement
}
if ( isActive()) {
e.preventDefault()
e.key === 'ArrowDown' ?
document.activeElement.nextElementSibling &&
document.activeElement.nextElementSibling.focus()
: e.key === 'ArrowUp' ?
document.activeElement.previousElementSibling &&
document.activeElement.previousElementSibling.focus()
:null
}
对于你的代码,我的观点是,正如@Alesky所建议的那样,使用可选的链式操作符来获取需要获取焦点的元素,或者将比较结果分配给你。e.key === 'ArrowDown'
到一个变量,并调用 focus()
的方法。
...
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault()
var baseEl = document && document.activeElement ;
var focusEl = e.key === 'ArrowDown'
? baseEl && document.activeElement.nextElementSibling
: baseEl && document.activeElement.previousElementSibling;
el.focus();
}
...