Javascript 用户在文本输入中键入时的 html 捕获事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13828450/
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
html catch event when user is typing into a text input
提问by Matt
Im just wondering how I go about catching the event when the user is typing into a text input field on my web application.
我只是想知道当用户在我的 Web 应用程序上的文本输入字段中键入时,我如何捕获事件。
Scenario is, I have a contacts listing grid. At the top of the form the user can type the name of the contact they are trying to find. Once there is more than 1 character in the text input I want to start searching for contacts in the system which contain those characters entered by the user. As they keep typing the data changes.
场景是,我有一个联系人列表网格。在表单的顶部,用户可以键入他们要查找的联系人的姓名。一旦文本输入中的字符超过 1 个,我想开始在系统中搜索包含用户输入的那些字符的联系人。当他们不断输入数据时,数据会发生变化。
All it is really is a simple type ahead type functionality (or autocomplete) but I want to fire off data in a different control.
它实际上只是一个简单的提前类型功能(或自动完成),但我想在不同的控件中触发数据。
I can get the text out of the input once the input has lost focus fine, but this doesnt fit the situation.
一旦输入失去焦点,我可以从输入中取出文本,但这不适合这种情况。
Any ideas?
有任何想法吗?
Thanks
谢谢
回答by adeneo
Use the keyup event to capture the value as the user types, and do whatever it is you do to search for that value :
使用 keyup 事件捕获用户键入的值,并执行任何操作来搜索该值:
$('input').on('keyup', function() {
if (this.value.length > 1) {
// do search for this.value here
}
});
Another option would be the inputevent, that catches any input, from keys, pasting etc.
另一种选择是input事件,它捕获来自键、粘贴等的任何输入。
回答by Hiram A
Why not use the HTML oninput event?
为什么不使用 HTML oninput 事件?
<input type="text" oninput="searchContacts()">
回答by syazdani
I would use the 'input' and 'propertychange' events. They fire on cut and paste via the mouse as well.
我会使用 ' input' 和 ' propertychange' 事件。它们也可以通过鼠标进行剪切和粘贴。
Also, consider debouncingyour event handler so that fast typists are not penalized by many DOM refreshes.
此外,请考虑对您的事件处理程序进行debounce,以便快速打字员不会受到许多 DOM 刷新的影响。
回答by Poya Eraghi
see my try:
看看我的尝试:
you should put .combo after every .input classes.
你应该把 .combo 放在每个 .input 类之后。
.input is a textbox and .combo is a div
.input 是一个文本框, .combo 是一个 div
$(".input").keyup(function(){
var val = this.value;
if (val.length > 1) {
//you search method...
}
if (data) $(this).next(".combo").html(data).fadeIn(); else $(this).next(".combo").hide().html("");
});
$(".input").blur(function(){
$(this).next(".combo").hide();
});

