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

Mir*_*lov 11 html-select selectedindex elm

我有一个<select>包含3个选项和<p>元素的HTML 元素.在<p>元素中我想打印当前所选项目的索引<select>.例如,如果我选择第一个选项,它应该打印0,如果我选择第二个选项,它应该打印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
Run Code Online (Sandbox Code Playgroud)

Mir*_*lov 18

有很多的不同的事件elm-html 2.0.0,但没有相关的<select>HTML元素.因此,您肯定需要一个可以使用的自定义事件处理程序on.它有一个类型:

on : String -> Decoder a -> (a -> Message a) -> Attribute
Run Code Online (Sandbox Code Playgroud)

每次在内部选择一个选项时触发的事件<select>称为"更改".你需要的是来自elm-community/html-extra的targetSelectedIndex,它使用了一个属性.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 }
Run Code Online (Sandbox Code Playgroud)

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

  • 这是一个与榆树0.17一起使用的"onSelect":[onSelect gist](https://gist.github.com/chalmagean/c0b2f874bcff728b3db047aa26b4e477) (2认同)