我想知道如何“美化”/“简化”以下代码:
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()
}
}
对我来说似乎太冗长了。
,我做错什么了吗?
我怎么写得更好?
发布于 2020-06-09 09:39:02
您可以使用可选的链接document?.activeElement?.nextElementSibling?.focus?.()
发布于 2020-06-09 09:43:57
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
}
发布于 2020-06-09 09:48:02
正如@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();
}
...
https://stackoverflow.com/questions/62288590
复制相似问题