javascript 我想要输入文本元素中的实时更改事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19893493/
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
I want a live change event in input text element
提问by Ramin
I want to handle change event in a text input field. but the event is triggered when the mouse loses focus on element.I want as-type-in change event triggered. what should i do for a live event in jQuery?
我想在文本输入字段中处理更改事件。但是当鼠标失去对元素的关注时会触发该事件。我想触发 as-type-in 更改事件。我应该为 jQuery 中的现场活动做什么?
I've used :
我用过:
jQuery('#element').on('change',function(){
//do the stuff
});
回答by Nasser Torabzade
you can use keyup()event:
您可以使用keyup()事件:
$('#someInput').keyup(function() {
// Your code here
});
there is also an input event:
还有一个输入事件:
$('#someInput').on('input', function() {
// Your code here
});
as frnhrpointed out, it's better to use inputevent because: "input will handle any change - e.g. if you paste something in the field, input will trigger but keyup wont."
正如frnhr指出的那样,最好使用input事件,因为:“输入将处理任何更改 - 例如,如果您在字段中粘贴某些内容,输入将触发但不会触发 keyup。”
回答by Napolux
You should use keyUp()
你应该使用 keyUp()
$( "#target" ).keyup(function() {
alert( "Handler for .keyup() called." );
});
回答by David says reinstate Monica
You've got three key-related events to choose from, keyup, keydownand keypress; assuming you type the string abc:
您可以从三个与键相关的事件中进行选择keyup,keydown和keypress;假设您输入字符串abc:
$('#demo').on('keyup', function(e){
console.log(this.value);
});
// a
// ab
// abc
$('#demo').on('keydown', function(e){
console.log(this.value);
});
//
// a
// ab
$('#demo').on('keypress', function(e){
console.log(this.value);
});
//
// a
// ab
The difference is, as the output (roughly) shows, is that keyupand keypressrespond beforethe value of the element is updated; so if you want to know the key that was pressed you have to use e.which(the jQuery normalized keypress event which returns the keyCodeof the pressed-key) in both the keypressand keyuphandlers and then add that to the valueproperty. e.whichwill, under keyupalsoreturn the correct keyCode, but you don'thave to manually add that key to get the updated value.
所不同的是,作为输出(大致)所示,是keyup和keypress响应之前的元素的值被更新; 因此,如果您想知道按下的键,则必须在和处理程序中使用e.which(jQuery 规范化按键事件,它返回keyCode按下的键的 ),然后将其添加到属性中。将,下也返回正确的,但您不必手动添加该密钥来获取更新的.keypresskeyupvaluee.whichkeyupkeyCodevalue

