[我想在有人修改可编辑表格单元格时更新我的模型。
onInput函数似乎在input
元素上运行良好,但是在带有td
的contenteditable="true"
元素上,永远不会调用处理函数。为什么?那我应该如何检测可编辑表格单元中的内容更改?
请参见下面的代码中的74和78行(我只是以Elm指南的“ buttons”示例为例,并在其中添加了一些东西,使它们变得最小但可运行):
module Main exposing (..)
-- Press buttons to increment and decrement a counter.
--
-- Read how it works:
-- https://guide.elm-lang.org/architecture/buttons.html
--
import Browser
import Html exposing (Html, button, div, text, table, tbody, tr, td, input)
import Html.Events exposing (onClick, onInput)
import Html.Attributes exposing (contenteditable)
-- MAIN
main =
Browser.sandbox { init = init, update = update, view = view }
-- MODEL
type alias Model = Int
init : Model
init =
0
-- UPDATE
type Msg
= Increment
| Decrement
update : Msg -> Model -> Model
update msg model =
case msg of
Increment ->
model + 1
Decrement ->
model - 1
testOnInputHandler : String -> Msg
testOnInputHandler str =
let
log = Debug.log "in testOnInputHandler" "here"
in
Increment
-- VIEW
view : Model -> Html Msg
view model =
div []
[ button [ onClick Decrement ] [ text "-" ]
, div [] [ text (String.fromInt model) ]
, button [ onClick Increment ] [ text "+" ]
, table []
[ tbody []
[ tr []
[ td [ contenteditable True, onInput testOnInputHandler] [ text "editable!" ]
]
]
]
, input [ onInput testOnInputHandler ] []
]
onInput
将从target.value
获取字符串,该字符串对于contenteditable
input
事件不存在。
例如,您可能想获取innerText
:
onContentEditableInput : (String -> msg) -> Attribute msg
onContentEditableInput tagger =
Html.Events.stopPropagationOn "input"
(Json.map (\x -> ( x, True )) (Json.map tagger innerText))
innerText : Json.Decoder String
innerText =
Json.at ["target", "innerText"] Json.string