如何 "美化""简化 "这段处理方向键和tabIndex的代码?[已关闭]

问题描述 投票:1回答:2

我想知道如何 "美化""简化 "下面的代码。

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.

是不是我做错了什么?

我怎样才能写得更好?

javascript ecmascript-6 ecmascript-5 ecmascript-7
2个回答
3
投票

你可以使用可选的链锁 document?.activeElement?.nextElementSibling?.focus?.()


2
投票
   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
  }

1
投票

对于你的代码,我的观点是,正如@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();
  }
...
© www.soinside.com 2019 - 2024. All rights reserved.