如何触发点击事件
How to trigger click event
在简单的 html + js 应用程序中,当我需要打开一些交互式输入元素(例如 input[type="file"]
或 input[type="date"]
或 input[type="color"]
)的对话时,任何非标准方式(使用按钮或页面加载)最直接的方式是 trigger click
event on above mentioned elements. But I couldn't find a way to do that in pure elm (without ports). I see for DOM events manipulation there is focus
trigger,但没有 click
。我错过了什么吗?不就是做事的"elm way"吗?
通过 MDN 阅读 File
元素,我看到他们建议使用 <label>
来触发没有 JavaScript
的元素:
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<label for="fileElem">Select some files</label>
elm-fileinputhttps://developer.mozilla.org/en/docs/Using_files_from_web_applications
找到 <input type="file">
的库:https://github.com/lovasoa/elm-fileinput。
此外,我还使用此库中的解码器提供了一个工作示例:https://runelm.io/c/ie0。
您可以(ab)使用 Html.attribute
可以接受任意字符串的方式(即 Html.attribute "onclick" "javascript:someFunction(this)"
)。在一些情况下,这是合理的,因为它可以提供最少的摩擦。例如,如果您想要一个聚焦隐藏文件输入的按钮,并且它很好地包装在一个 component/view 文件中,它总是一个按钮后跟一个文件输入,这是有道理的:
import Html exposing (..)
import Html.Attributes as Attr exposing (..)
import Html.Events exposing (on)
filePick : Html msg
filePick =
div [ class "file-pick-wrapper" ]
[ button
[ type_ "button"
, attribute "onclick" "javascript:this.nextElementSibling.click()"
]
[ text "Choose a File" ]
, input
[ type_ "file"
, on "change" someMsgDecoder
, style [ ( "display", "none" ) ]
]
[]
]
从那里您可以让 someMsgDecoder
使用 Json.Decode
读取 at [ "target", "files", "0", "name" ]
文件名。
在简单的 html + js 应用程序中,当我需要打开一些交互式输入元素(例如 input[type="file"]
或 input[type="date"]
或 input[type="color"]
)的对话时,任何非标准方式(使用按钮或页面加载)最直接的方式是 trigger click
event on above mentioned elements. But I couldn't find a way to do that in pure elm (without ports). I see for DOM events manipulation there is focus
trigger,但没有 click
。我错过了什么吗?不就是做事的"elm way"吗?
通过 MDN 阅读 File
元素,我看到他们建议使用 <label>
来触发没有 JavaScript
的元素:
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<label for="fileElem">Select some files</label>
elm-fileinputhttps://developer.mozilla.org/en/docs/Using_files_from_web_applications
找到 <input type="file">
的库:https://github.com/lovasoa/elm-fileinput。
此外,我还使用此库中的解码器提供了一个工作示例:https://runelm.io/c/ie0。
您可以(ab)使用 Html.attribute
可以接受任意字符串的方式(即 Html.attribute "onclick" "javascript:someFunction(this)"
)。在一些情况下,这是合理的,因为它可以提供最少的摩擦。例如,如果您想要一个聚焦隐藏文件输入的按钮,并且它很好地包装在一个 component/view 文件中,它总是一个按钮后跟一个文件输入,这是有道理的:
import Html exposing (..)
import Html.Attributes as Attr exposing (..)
import Html.Events exposing (on)
filePick : Html msg
filePick =
div [ class "file-pick-wrapper" ]
[ button
[ type_ "button"
, attribute "onclick" "javascript:this.nextElementSibling.click()"
]
[ text "Choose a File" ]
, input
[ type_ "file"
, on "change" someMsgDecoder
, style [ ( "display", "none" ) ]
]
[]
]
从那里您可以让 someMsgDecoder
使用 Json.Decode
读取 at [ "target", "files", "0", "name" ]
文件名。