jQuery 在淘汰赛 JS 中使用按键事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18897529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using keypress event in knockout JS
提问by divyanshm
I'm trying to read the contents of an html textbox and fetch data from an API to accomplish a google style auto complete. I'm using twitter bootstrap typeahead
for the auto complete functionality. For that I need to record keys as they are pressed and make the API call with the query text.
我正在尝试读取 html 文本框的内容并从 API 获取数据以完成谷歌风格的自动完成。我正在使用twitter bootstrap typeahead
自动完成功能。为此,我需要在按键按下时记录它们并使用查询文本进行 API 调用。
The html for the text box is this
文本框的 html 是这样的
<input id="query" data-bind="value: query, valueUpdate: 'keypress', event: { keypress: check }"/>
My assumption was that this will update the value in the viewmodel as soon as the key is pressed, and the check
function will meanwhile call into the API. But the call is made to check( ) and the text box never gets populated when the user types. if the JS looks like this -
我的假设是这将在按下键后立即更新视图模型中的值,同时该check
函数将调用 API。但是调用 check() 并且在用户键入时永远不会填充文本框。如果 JS 看起来像这样 -
function check() {
alert("Hello");
}
For every key I press, hello pops up but the text box in the HTML UI does not show the key that was pressed/does not record which key was pressed. How do I record the key press and send the request simultaneously?
对于我按下的每个键,hello 都会弹出,但 HTML UI 中的文本框不显示按下的键/不记录按下的键。如何记录按键操作并同时发送请求?
回答by egucciar
- make sure query is an observable
- use
valueUpdate = 'afterkeydown'
- use
event: { 'keyup': check }:
- 确保查询是可观察的
- 用
valueUpdate = 'afterkeydown'
- 用
event: { 'keyup': check }:
Also I'd use console.log if possible as opposed to alert, and log the query so you can make sure the value is updating. :) you also my want to log the event like this
此外,如果可能,我会使用 console.log 而不是警报,并记录查询,以便确保值正在更新。:) 你也想像这样记录事件
function check(data, event) {
console.log(event);
}
that will tell you the keycode for the key you pressed
这会告诉你你按下的键的键码
回答by CSSian
This thread is old, but I've noticed it doesn't cite use of KO's textInputbinding. This is a new feature added in v3.2.0.
这个线程很旧,但我注意到它没有引用 KO 的textInput绑定的使用。这是 v3.2.0 中添加的新功能。
The KO docs, at least as of now (Jan-2015), specifically addresses this issue:
至少截至目前(2015 年 1 月),KO 文档专门解决了这个问题:
Note 1: textInput vs value binding
注 1:textInput 与值绑定
Although the value binding can also perform two-way binding between text boxes and viewmodel properties, you should prefer textInput whenever you want immediate live updates.
尽管值绑定也可以在文本框和视图模型属性之间执行双向绑定,但无论何时您想要即时实时更新,您都应该首选 textInput。
See http://knockoutjs.com/documentation/textinput-binding.html