在html文本输入框中输入文本时,如何执行jquery函数?

Sha*_*e S 4 html jquery

我有类似的HTML代码

<input type="text" class="input-box">
Run Code Online (Sandbox Code Playgroud)

输入框填充4个字符时,我想执行jQuery函数。

例如,我键入“ ABCD”,则将执行该函数,而不是针对“ AB”或“ ABC”之类的东西。我怎样才能做到这一点?

Pra*_*lan 5

绑定事件处理程序并检查文本长度,根据长度调用函数

$('.input-box').on('input', function() {
  if (this.value.trim().length >= 4) {
    // call your function here
    doIt();
  }
});

function doIt() {
  alert('hi');
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="input-box">
Run Code Online (Sandbox Code Playgroud)