【问题标题】:Correct typing for nextElementSibling so .focus() can be used?正确键入 nextElementSibling 以便 .focus() 可以使用?
【发布时间】:2019-06-22 18:13:36
【问题描述】:

我正在尝试使用 nextElementSibling 以编程方式将焦点转移到我的表单中,但是我也在使用 Typescript 并希望输入我的变量/常量...

我已经成功没有输入,并使用以下内容:

myFunct(event) {
  const myEl = event.srcElement;
  const nextElement = myEl.nextElementSibling;

  if (nextElement) {
    nextElement.focus();
  }
}

但是,在代码上使用类型时,我遇到了不一致和以下 IntelliJ 警告:

“元素”类型上不存在属性“焦点”

myFunct(event: KeyboardEvent) {
  const myEl: Element = event.srcElement;
  const nextElement: Element = myEl.nextElementSibling;

  if (nextElement) {
    nextElement.focus();
  }
}

但是在谷歌上搜索,我发现nextElementSibling 的类型实际上应该是Element,根据Mozilla

有人可以帮忙吗?

更新:

看来event 上的KeyboardEvent 实际上是导致问题的原因..

【问题讨论】:

    标签: javascript html typescript types element


    【解决方案1】:

    来自MDN:Element 从其父元素 Element 继承属性,并从 GlobalEventHandlers 和 TouchEventHandlers 实现这些属性。

    因此,您可以将代码更改为(使用typescriptlang.org 测试的代码):

    function myFunct(event: KeyboardEvent) {
      const myEl = <HTMLElement>event.srcElement;
      const nextElement = <HTMLElement>myEl.nextElementSibling;
    
      if (nextElement) {
        nextElement.focus();
      }
    }
    

    【讨论】:

    • 啊!我忘记了以这种方式强制打字。像const nextElement: HTMLElement = &lt;HTMLElement&gt;myEl.nextElementSibling这样写会不会有点矫枉过正?
    • @physicsboy 不,这是一个错误。你可以在 [typescriptlang.org](typescriptlang.org/play) 上看到它的实际效果
    猜你喜欢
    • 2013-08-26
    • 2016-05-29
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2014-06-21
    相关资源
    最近更新 更多