elm - 使用“单击”事件处理程序访问属性名称
问题描述
我试图在单击时访问元素 HTML 属性。我发现它Events.onClick
只会返回event.target.value
,我需要用来Events.on
处理自定义行为。
我需要的是:当单击 a 时,div
我现在应该能够访问其 HTML 属性,id
并name
发送此值以更新一些消息。
我试过这样:
onClickData : msg -> Attribute msg
onClickData handler =
on "click" (Decode.succeed handler )
---
view: ...
....
div[onClickData HandleClick] []
这样,我可以HandleClick
在单击时触发操作,div
但无法访问其 HTML 属性。
解决方案
正如@glennsl 所指出的,您通常想要做更多这样的事情:
view identification =
button [ id identification, onClick (MyMsg identification) ]
[ text "Click me"
]
即您可以将数据直接传递到您的Msg
类型中。
也就是说,您可能希望在一些不寻常的互操作情况下执行此操作。一般原则是您可以从 from 获取您绑定事件处理程序的元素event.currentTarget
,因此您可以使用以下解码器:
decodeProperty : String -> Decoder a -> Decoder a
decodeProperty property decoder =
Decode.at ["currentTarget", property] decoder
--- use
onClickId : (String -> msg) -> Attribute msg
onClickId tagger =
on "click" (Decode.map tagger (decodeProperty "id"))
推荐阅读
- xamarin - 如何在 GRID 上正确设置高度?
- python - Django:根据父模型查询多个模型
- javascript - 当 a 是数组时: t = a 和 t = [...a] 有什么区别?
- android - android - 矢量资产图标多种显示尺寸支持
- mysql - PHP 7.2 分组方式
- python - Bazel 更改 .so 的文件名,使其无法导入
- python - 如何在 QMainWindow 上显示自定义的 QSplitter 类
- c# - 如何从 ManagedObjectReference 释放对对象的引用?
- android - Mockito 错误 -“与此模拟的交互为零”
- pandas - 从 RDD 中的 Pandas DataFrames 创建 Spark DataFrame