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

如何为Hyperscript中查找的元素动态分配change事件?

问题描述

我有一个绑定在特定input上的change事件,运行完全正常:

<input name="company_addresses[0][vat_number]" id="company-profile-vat" type="text" class="form-control"
  value="<%=render?.data?.mes?.company_addresses[0]?.vat_number%>"
  _="on change make a Date called timestamp then put timestamp.toISOString() into the #company-address-updated.value">

但我想要将该事件动态分配给多个元素。因此我在页面顶部编写了如下脚本:

<div id="content-form" _="on load 
repeat for foreignInput in <input[name*='][']:not([name*='][serial_']):not([name*='][updated']), textarea[name*='][']:not([name*='][serial_']):not([name*='][updated']), select[name*='][']:not([name*='][serial_']):not([name*='][updated'])/>
  set inputTarget to foreignInput.name.split('][')[0]+'][updated' 
  repeat for foreignInputUpdateInput in <input[name*=`${inputTarget}`]/&gt;
    log foreignInputUpdateInput 
     
    end
  end
end
"> 

目前我已成功找到所有目标元素,但不知道如何为这些找到的元素分配事件。我尝试了如下写法但无效:

on change from inputTarget
  make a Date called timestamp then put timestamp.toISOString() into the foreignInputUpdateInput.value
end

我希望尽可能避免使用JavaScript,请问该如何实现?


解决方案

用Hyperscript的install命令就能解决,它专门用来给元素动态绑定行为,完全不需要额外JS。修改你的循环逻辑,直接在遍历元素时为每个输入框安装change事件:

<div id="content-form" _="on load 
repeat for foreignInput in <input[name*='][']:not([name*='][serial_']):not([name*='][updated']), textarea[name*='][']:not([name*='][serial_']):not([name*='][updated']), select[name*='][']:not([name*='][serial_']):not([name*='][updated'])/>
  set inputTarget to foreignInput.name.split('][')[0]+'][updated' 
  repeat for foreignInputUpdateInput in <input[name*=`${inputTarget}`]/&gt;
    install on change from foreignInput
      make a Date called timestamp 
      put timestamp.toISOString() into foreignInputUpdateInput.value
    end
  end
end
"> 

关键说明

  • install会把后续的事件逻辑直接附加到指定的foreignInput上,每个循环迭代都会为当前元素创建独立的事件绑定,不会和其他元素的逻辑冲突。
  • 循环内的foreignInputUpdateInput在install的代码块中可直接使用,会自动关联到当前输入框对应的更新字段,完美复刻单个元素的事件逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 16:13:10