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

如何使用Hyperscript触发HTML5 dialog元素?

如何用Hyperscript触发dialog元素

不清楚如何使用Hyperscript触发dialog元素,我的代码如下:

<dialog id="mydialog">
  <button autofocus onclick="document.querySelector('dialog').close();">Close</button>
  <p>This modal dialog has a groovy backdrop!</p>
</dialog>
<button onclick="document.querySelector('dialog').showModal()">Show the dialog (JS)</button>
<button _="on click send showModal() to #mydialog">Show the dialog (HS)</button>

问题分析

你使用的Hyperscript语法有误,send showModal() to #mydialog并不是Hyperscript调用元素方法的正确写法。

修正方案

Hyperscript调用DOM元素方法的正确方式是先选中目标元素,再调用其方法,以下是两种可行的写法:

写法一:直接调用方法

<button _="on click call document.querySelector('#mydialog').showModal()">Show the dialog (HS)</button>

写法二:使用Hyperscript的元素选择语法

<button _="on click get #mydialog then call it.showModal()">Show the dialog (HS)</button>

如果要把关闭按钮也换成Hyperscript写法,保持代码风格统一,可以这样写:

<button autofocus _="on click get #mydialog then call it.close()">Close</button>

完整修正代码

<dialog id="mydialog">
  <button autofocus _="on click get #mydialog then call it.close()">Close</button>
  <p>This modal dialog has a groovy backdrop!</p>
</dialog>
<button onclick="document.querySelector('dialog').showModal()">Show the dialog (JS)</button>
<button _="on click get #mydialog then call it.showModal()">Show the dialog (HS)</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:58:19