本文介绍了如何在Elm中打印所选选项的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个 < select> ; HTML元素,带有3个选项和 < p> 元素。在< p> 元素中,我要在< select> 中打印当前所选项目的索引。例如。如果选择第一个选项,则应打印0,如果选择第二个选项,则应打印1,依此类推。我如何从下面给出的最小代码开始?I have a <select> HTML element with 3 options and a <p> element. In the <p> element I want to print index of the currently selected item in <select>. E.g. if I select the first option, it should print 0, if I select the second option, it should print 1, and so on. How do I proceed from the minimal code, which is given below?import Html as H exposing (Html)import Maybeimport Signal as S exposing (Address, (<~))type alias Model = { selected : Maybe Int }model = { selected = Nothing }type Action = NoOp | Select Intupdate action model = case action of NoOp -> model Select n -> { model | selected <- Just n }view address model = H.div [] [ H.select [] [ H.option [] [ H.text "0" ] , H.option [] [ H.text "1" ] , H.option [] [ H.text "2" ] ] , H.p [] [ H.text <| Maybe.withDefault "" <| Maybe.map toString model.selected ] ]actions = Signal.mailbox NoOpmain = view actions.address <~ S.foldp update model actions.signal推荐答案有很多不同事件在 elm-html 2.0.0 ,但什么也没有与< select> HTML元素相关。因此,您肯定需要一个自定义事件处理程序,可以使用 上的。它的类型为:There's a lot of different events in elm-html 2.0.0, but nothing relevant to the <select> HTML element. So you definitely need a custom event handler, which you can create using on. It has a type:on : String -> Decoder a -> (a -> Message a) -> Attribute每次在<中选择一个选项时触发的事件; select> 称为更改 。您需要的是来自 elm-community / html-extra 的targetSelectedIndex >使用了 selectedIndexThe event that is triggered every time you select an option inside the <select> is called "change". What you need is targetSelectedIndex from elm-community/html-extra which ustilizes a selectedIndex property.最终代码如下:更新为Elm-0.18Updated to Elm-0.18import Html exposing (..)import Html.Events exposing (on, onClick)import Html.Attributes exposing (..)import Json.Decode as Jsonimport Html.Events.Extra exposing (targetSelectedIndex)type alias Model = { selected : Maybe Int }model : Modelmodel = { selected = Nothing }type Msg = NoOp | Select (Maybe Int)update : Msg -> Model -> Modelupdate msg model = case msg of NoOp -> model Select s -> { model | selected = s }view : Model -> Html Msgview model = let selectEvent = on "change" (Json.map Select targetSelectedIndex) in div [] [ select [ size 3, selectEvent ] [ option [] [ text "1" ] , option [] [ text "2" ] , option [] [ text "3" ] ] , p [] [ text <| Maybe.withDefault "" <| Maybe.map toString model.selected ] ]main : Program Never Model Msgmain = beginnerProgram { model = model, view = view, update = update }您可以在此处的浏览器中运行 https://runelm.io/c/xumYou can run it in browser here https://runelm.io/c/xum 这篇关于如何在Elm中打印所选选项的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-28 07:30