首页 > 解决方案 > 使用“单击”事件处理程序访问属性名称

问题描述

我试图在单击时访问元素 HTML 属性。我发现它Events.onClick只会返回event.target.value,我需要用来Events.on处理自定义行为。

我需要的是:当单击 a 时,div我现在应该能够访问其 HTML 属性,idname发送此值以更新一些消息。

我试过这样:

onClickData : msg -> Attribute msg
onClickData handler =
    on "click" (Decode.succeed handler )
---
view: ...
    ....
    div[onClickData HandleClick] []

这样,我可以HandleClick在单击时触发操作,div但无法访问其 HTML 属性。

标签: elm

解决方案


正如@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"))


推荐阅读