当用户按下键盘 5 次时执行 ajax 函数

Execute ajax function when the user press 5 times his keyboard

我想执行一个 ajax 函数。当且仅当用户按下键盘 5 次时,才必须执行此 ajax 函数。

我对 ajax 请求使用 Jquery。

我试过了,但还是不行:

// What i tried to do 
$("#num_cppap").keypress(function(event){
if (event.which == 5){
// The AJAX function
$( "#num_cppap" )
       .focusout(function() {
        var numCppap = $(this).val();
        var isBizarre = false;
        var searchBy5Chars = false;
        if(numCppap.length > 0) {
            if(numCppap.length == 5){
                searchBy5Chars = true;
                $.ajax({
                    type : "POST",
                    url : '/gestion/gestDepot/ajaxrecherchecppap',
                    async : false,
                    dataType : 'json',
                    data : {
                        'num_publication' : numCppap,
                        'isBizarre' : isBizarre,
                        'searchBy5Chars' : searchBy5Chars
                    },
                    success : function(publication) {
                        if ($.isEmptyObject(publication)) {
                            resetTitreDepot('num_cppap');
                            alert('Le numéro de CPPAP ne correpond à aucun contrat.');
                        } else {
                            $(this).dialog('close');
                            $("#noPublicationCPPAP").hide();

                            gestionTitreDepot(publication);
                        }

                   }
                 });
             }
         } 
        else {
            resetTitreDepot('num_cppap');
        }
    })
    }
    else {
        alert('you stupid');
    }
});

如果你有一些文档或东西可以帮助我,那就太好了!

感谢您的关注!

您可以创建一个像 var number=0; 这样的变量,然后在 keypress 函数中增加它:number++;

然后将您想要 运行 的代码放入以下 ​​if 语句中:

if(number==5){...}

这意味着每按一个键,数字就会增加,一旦达到5,if(number==5){...}里面的代码就会运行。

这是一个基本示例:

$(function(){
var number=0;
$("#text").on("keypress",function(){
number++;
if(number==5){
alert("Pressed 5 times!");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Write 5 characters here" id="text">

或者如果您希望每次按键 5 次时 运行,您只需将 if(number==5) 替换为 if(number%5==0)

$(function(){
var number=0;
$("#text").on("keypress",function(){
number++;
if(number%5==0){
alert("Pressed 5 times!");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Write 5 characters here" id="text">

你也可以在你的函数中实现这个方法,在 ajax 调用之前,这样写:if(number==5)if(number%5==0)。然后 ajax 只会 运行 如果任何键被按下 5 次。