javascript 在输入框中键入单个字母后使用 jQuery 触发函数

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

Trigger a function with jQuery after a single letter was typed in an input box

javascriptjquerykeyup

提问by lukeshek

I'm trying to make a simple search box. How can I trigger a function just after a single letter was typed in an input box? I used .keyup, but this seems to be useless, because when a diacritic character is typed, the function is triggered three times.

我正在尝试制作一个简单的搜索框。如何在输入框中输入一个字母后立即触发功能?我使用了.keyup,但这似乎没用,因为当输入变音符号时,该函数会被触发3次。

<input id="text" type="text" />
<div></div>
<script>
    $('#text').keyup(function(){
        $('div').append('TEST'+$(this).val());
    });
</script>

The above code works fine unless you type any diacritic character: ?, ?, ?, ?, ?, ?, etc.

除非您输入任何变音符号,否则上述代码工作正常:?, ?, ?, ?, ?, ? 等。

I can't use .keypress or .keydown since they trigger a function before a character is typed.

我不能使用 .keypress 或 .keydown 因为它们在输入字符之前触发一个函数。

EDITED LATER:

稍后编辑:

I know that my example might not be clear enough to understand the problem, but... In my real code every time a letter is typed, an SQLite query is executed. If a type a diacritic character or a capital letter, the query is executed three or two times, which slows down the whole script. It won't make a big difference if you execute the script in a computer web browser, but there is significant lag in mobile browsers.

我知道我的例子可能不够清楚,无法理解问题,但是......在我的真实代码中,每次输入一个字母时,都会执行一个 SQLite 查询。如果输入变音符号或大写字母,则查询会执行三到两次,这会减慢整个脚本的速度。如果您在计算机 Web 浏览器中执行脚本,则不会有太大区别,但在移动浏览器中会出现明显滞后。

回答by Tina CG Hoehr

I considered checking the value of the string compared to the last time it was changed. So keypresses don't run the function unless it causes the string to be changed.

我考虑过检查字符串与上次更改时相比的值。所以按键不会运行该函数,除非它导致字符串被更改。

http://jsfiddle.net/82sTJ/1/

http://jsfiddle.net/82sTJ/1/

回答by Landin Martens

var i = 0;    

$('#text').keyup(function(event) {
    i++;
    if(i == 1)
    {
        $('div').append('TEST'+$(this).val());
    }
});

This to me should work, you could also detect the specific key being entered

这对我来说应该有效,您还可以检测到正在输入的特定键