如何向当前元素的相对位置的元素发送事件

问题描述

我有一个类为 .node-display 的元素列表,当一个元素被点击时,它变成了一个输入。我想捕获向下或向上箭头键以单击列表中的下一个 .node-display(相对于当前元素)。

在下面的例子中,按下会点击第 5 项,向上按下会点击第 3 项。

  • 1
  • 2
  • 3
  • 4(当前选中)
  • 5
  • 6

我最好的猜测是这样的。

<input
   _="on keyup[key is 'ArrowDown'] send click to the first .node-display end"
>

有谁知道我实际上是怎么写这个表达式的?

解决方法

您可能希望将行为放在父 ul 上,这样您就不必在每次输入时都重复它。

像这样:

<ul _="on keydown[key is 'ArrowDown'] from <input/> in me
           set nextSibling to it's parentElement's nextElementSibling
           if nextSibling
             set nextInput to the first <input/> in nextSibling
             call nextInput.focus()
             halt
           end
       on keydown[key is 'ArrowUp'] from <input/> in me
           set previousSibiling to it's parentElement's previousElementSibling
           if previousSibiling
             set previousInput to first <input/> in previousSibiling
             call previousInput.focus()
             halt
           end
       ">
  <li><input/></li>
  <li><input/></li>
  <li><input/></li>
  <li><input/></li>
</ul>

关于此代码的一些说明:

  • 我在事件处理程序中使用 from from,它将事件来自的元素放入 it 符号
  • 我正在使用 keydown 事件,因此我们可以使用 halt 命令取消该事件,以避免向下和向上键改变插入符号位置
  • 我正在使用 halt 命令阻止事件传播
  • 我使用 focus 而不是点击作为概念证明