javascript 第三个字符后的操作键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4511085/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 13:57:23  来源:igfitidea点击:

action keyup after the third charecter

javascriptjquery

提问by Andy

Hi could someone help me figure out how to stop a function running until a specific number of characters are pressed?

嗨,有人可以帮我弄清楚如何在按下特定数量的字符之前停止运行函数吗?

currently using the following function:

目前使用以下功能:

$('input#q').keyup

this works as soon as you press any key...

只要您按任意键,这就会起作用...

回答by subhaze

Something like this should start firing code after 3 letters have been added:

添加 3 个字母后,这样的事情应该开始触发代码:

Live Example

现场示例

JavaScript

JavaScript

$('input#q').keyup( function() {
   if( this.value.length < 4 ) return;
   /* code to run below */
   $('#output').val(this.value); 
});

HTML

HTML

<input id="q" />
<br /><br />
<input id="output"/>

回答by picus

you could do :

你可以这样做:

$('input#q').keyup(function(){
  if($(this).val().length > 3)
  {
    //do something
  }
});

回答by ollie

You could store the characters in a string variable each time a key is pressed and then run a conditional statement to check the length of the variable. If it's equal to three, run whatever function

您可以在每次按下键时将字符存储在字符串变量中,然后运行条件语句来检查变量的长度。如果等于三,运行任何函数

回答by Pointy

Well you'll probably need to take into account the way focus changes. Do you want to clear the counter when the field is newly focused or not? You should also decide whether you're counting characters actually added to the field, or instead if you want to could actual discrete key presses - a "shift" key press, for example, won't add any characters, but it's a key being pressed.

那么您可能需要考虑焦点变化的方式。当该领域新聚焦或不集中时,您想清除计数器吗?您还应该决定是否计算实际添加到字段中的字符,或者如果您想要实际的离散按键 - 例如,“shift”按键不会添加任何字符,但它是一个关键按下。

Anyway it'd probably be something like this:

无论如何,它可能是这样的:

$(function() {
  var keyCount = 0;
  $('#q').keyup(function() { // "keypress" to count characters
    if (++keyCount === 3) {
      // do the thing
    }
  })
  .focus(function() {
    keyCount = 0; // if this is what you want
  });
});

If you're counting the "keypress" event instead of "keyup", you might want to count the actual length of the text field value rather than trying to count events.

如果您计算的是“keypress”事件而不是“keyup”,您可能想要计算文本字段值的实际长度,而不是尝试计算事件数。

回答by Ben Clayton

How's about:

怎么样:

var c = 0;
('input#q').keyup( function() {
   c++;
   if (c >= 3) {
      startGame();
   }
} );