【问题标题】:How to send an event to a element in a relative position of the current element如何向当前元素的相对位置的元素发送事件
【发布时间】:2021-08-19 18:29:59
【问题描述】:

我有一个类.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"
>

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

【问题讨论】:

  • 我把你的问题转发到了discord频道。

标签: htmx hyperscript


【解决方案1】:

您可能希望将行为放在父 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,它将事件来自的元素放入it符号中
  • 我正在使用keydown 事件,因此我们可以使用halt 命令取消该事件,以避免向下和向上键改变插入符号的位置
  • 我正在使用halt 命令阻止事件传播
  • 我使用 focus 而不是点击作为概念证明

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 2015-12-21
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    相关资源
    最近更新 更多