我希望能够将输入的文本值存储在变量中。我认为类似的东西会起作用:
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/