You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Hyperscript查找点击元素的最近.foo父元素

正确实现方式

你需要使用Hyperscript的函数调用语法来调用DOM元素的closest()方法,正确写法是通过.运算符连接元素与方法名,参数放在括号内:

<div _="on click log target.closest(.foo)">
  <details class="foo"><summary>AAA</summary>aaa</details>
  <details class="foo"><summary>BBB</summary>bbb</details>
</div>

为什么之前的写法失败?

你之前尝试的所有写法用了自然语言式表述(比如target's closest .foo),但Hyperscript的语法规则要求:

  • 调用元素方法必须用.连接元素与方法名
  • 方法参数需放在括号内,选择器直接写为.foo即可(无需额外引号包裹)

其他等价正确写法

  • 明确上下文的写法:
    <div _="on click log the closest(.foo) from target">
    
  • 更简洁的写法:
    <div _="on click log closest(.foo) on target">
    

以上写法都会正确定位到点击元素的最近.foo父元素,并将其打印到控制台。

内容的提问来源于stack exchange,提问作者phi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 06:59:54