如何检查是否有人在输入类型文本上添加了 4 个或更多字母?

How to check if someone has added 4 letters or more on input type text?

使用下面的脚本对我的文件 veriUSPF.php 进行了 ajax 调用,在此文件中我有一个 SELECT 查询来检查用户名是否可用。执行下面的脚本 onBlur,但我希望它仅在有人在输入中添加 4 个或更多字母时才执行 ajax 调用,这可能吗?

html:

<input id="UsName" type="text" minlength="4" maxlength="17" autocomplete="off" onBlur="checkAvailability()" value="<?php echo htmlentities($username, \ENT_QUOTES, 'UTF-8', false); ?>" name="changeUsernamePF">
<span id="user-availability-status"></span>

脚本:

function checkAvailability() {
    jQuery.ajax({
        url: siteURL + "/veriUSPF.php",
        data: "changeUsernamePF=" + $("#UsName").val(),
        type: "POST",
        success: function(a) {
            $("#user-availability-status").html(a)
        }
    })
}

您可以使用输入事件:

$('#UsName').on('input', function(e) {
    if (this.value.length>=4) {
        console.log('call ajax now');
    }
}).trigger('input');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="UsName" type="text" minlength="4" maxlength="17" autocomplete="off" onBlur="checkAvailability()" value="" name="changeUsernamePF">
<span id="user-availability-status"></span>

使用内联事件,您可以编写:

function checkAvailability(e, ele) {
  if (ele.value.length>=4) {
      console.log('call ajax now');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input id="UsName" type="text" minlength="4" maxlength="17" autocomplete="off" oninput="checkAvailability(event, this)" value="" name="changeUsernamePF">
<span id="user-availability-status"></span>