如何在 Elm 中打印所选选项的索引?

How to print index of selected option in Elm?

我有一个 <select> HTML element with 3 options and a <p> 元素。在 <p> 元素中,我想打印 <select> 中当前 selected 项目的索引。例如。如果我 select 第一个选项,它应该打印 0,如果我 select 第二个选项,它应该打印 1,依此类推。我如何从下面给出的最小代码开始?

import Html as H exposing (Html)
import Maybe
import Signal as S exposing (Address, (<~))

type alias Model = { selected : Maybe Int }
model = { selected = Nothing }

type Action = NoOp | Select Int
update 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 NoOp
main = view actions.address <~ S.foldp update model actions.signal

有很多 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。它有一个类型:

on : String -> Decoder a -> (a -> Message a) -> Attribute

每次 select <select> 中的选项触发的事件称为 “change”. What you need is targetSelectedIndex from elm-community/html-extra which ustilizes a selectedIndex 属性.

最终代码如下所示:

更新到 Elm-0.18

import Html exposing (..)
import Html.Events exposing (on, onClick)
import Html.Attributes exposing (..)
import Json.Decode as Json
import Html.Events.Extra exposing (targetSelectedIndex)


type alias Model =
    { selected : Maybe Int }


model : Model
model =
    { selected = Nothing }


type Msg
    = NoOp
    | Select (Maybe Int)


update : Msg -> Model -> Model
update msg model =
    case msg of
        NoOp ->
            model

        Select s ->
            { model | selected = s }


view : Model -> Html Msg
view 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 Msg
main =
    beginnerProgram { model = model, view = view, update = update }

您可以在此处 运行 在浏览器中 https://runelm.io/c/xum