用户输入上的榆树自动完成功能

时间:2016-01-29 20:23:51

标签: javascript autocomplete user-input elm

我对榆树很新。我在网页上有一个输入字段。当用户输入输入字段时,我想查询单词列表(存储在initialModel中)并根据输入字段中输入的内容给出完成建议。我想我需要Html.Events用于按键,所以我已经导入了它。我知道我还需要一个更新功能,所以我已经包含了空功能。这是我到目前为止的代码。提前谢谢。

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)

import StartApp.Simple as StartApp

-- MODEL

type alias Model =
  {
    words: List String
  }

initialModel : Model
initialModel =
  {
    words =
      [ "chair", "sofa", "table", "stove", "cabinet", "tv", "rug", "radio", "stereo" ]
  }


-- UPDATE
update =
  {

  }


-- VIEW

title : String -> Html
title message =
  message
    |> Html.text


pageHeader : Html
pageHeader =
  h1
    [  ]
    [ title "Hello" ]


pageFooter : Html
pageFooter =
  footer
    [  ]
    [ a [ href "#" ]
        [ text "Hello" ]
    ]

inputField : Html
inputField =
  input
    [ type' "text" ]
    [ ]


view : Html
view =
  div
    [ id "container" ]
    [ pageHeader
      , inputField
      , pageFooter
    ]

-- BRING MODEL, VIEW AND UPDATE TOGETHER

main =
  view
  -- StartApp.start
  --   {
  --     model = initialModel
  --     , view = view
  --     , update = update
  --   }

1 个答案:

答案 0 :(得分:2)

您的模型需要跟踪文本框的当前值。您可以在SetValue函数期间创建更新model.value的update操作开始:

type alias Model =
  { value : String
  , words : List String
  }

initialModel : Model
initialModel =
  { value = ""
  , words =
      [ "chair", "sofa", "table", "stove", "cabinet", "tv", "rug", "radio", "stereo" ]
  }

type Action
  = SetValue String

update action model =
  case action of
    SetValue value ->
      { model | value = value }

您还需要在输入到该文本框时触发更新功能。您可以使用on event attribute执行此操作。通常会收听输入事件,这会为您提供比个别按键事件更多的信息:

inputField : Address Action -> Html
inputField address =
  input
    [ type' "text"
    , on "input" targetValue (Signal.message address << SetValue)
    ]
    [ ]

最后,您需要显示包含自动填充内容的div:

autocomplete model =
  let
    matches =
      List.filter (startsWith model.value) model.words
  in
    div []
      [ div [] [ text <| "Autocomplete input: " ++ model.value ]
      , div [] [ text "Autocomplete matches: " ]
      , div [] <| List.map (\w -> div [] [ text w ]) matches
      ]

如果您决定变得更复杂并希望使用外部源进行自动完成,则需要切换到StartApp而不是StartApp.Simple,因为它支持效果和任务。

上面的代码段依赖于您最初发布的内容的一些其他更改,因此我发布了gist with a working example,您可以将其插入http://elm-lang.org/try。希望这有帮助!