javascript - 如何在 mithril.js 中使用输入标签的 'value'

标签 javascript mithril.js

我希望能够将输入的文本值存储在变量中。我认为类似的东西会起作用:

m('input', {
    placeholder: 'Type to search...',
    oninput: () => { alert(this.value) }
})

我使用alert()只是为了测试它。每当给出输入时,它只会给出一条消息“未定义”。

最佳答案

箭头函数 () => {} 没有 this。为了依赖将 this 绑定(bind)到触发事件的元素的事件处理程序,您必须使用:

// the traditional function form...
m('input', {
    placeholder: 'Type to search...',
    oninput: function(){ alert(this.value) }
})

// ...or the modern method shorthand:
m('input', {
    placeholder: 'Type to search...',
    oninput(){ alert(this.value) }
})

或者,您可以完全避免 this (它毕竟是不明确的,正如我们刚刚看到的),保留箭头函数,并使用作为事件处理程序的第一个参数提供的事件对象:

m('input', {
    placeholder: 'Type to search...',
    oninput: e => { alert(e.target.value) }
})

关于javascript - 如何在 mithril.js 中使用输入标签的 'value',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60617529/

相关文章:

javascript - 如何使通过 useState 钩子(Hook)改变状态的函数可重用?

javascript - 使用 Google map 中的坐标列表创建路线

java - 使用 WebSockets 实现 WebRTC 信令

javascript - backbone.js collection.get() 未定义

javascript - 如何在 localStorage 的 mirthril.js 中存储状态?

javascript - 如何更新数组中的 map 对象?

javascript - AJAX错误: 400 Bad Request

Mithril.js 多个 css 类

javascript - Mithril js - 跨组件通信模式

javascript - 跟踪 mithril.js 自动重画系统