在 Ajax 调用后向 JQuery keyup() 添加延迟 [英] Adding a delay to JQuery keyup() after Ajax call

查看:36
本文介绍了在 Ajax 调用后向 JQuery keyup() 添加延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个非常棘手的问题,我不知道如何解决.我连续有几个文本框,我需要填写这些文本框.每次填充文本框时,我都会获取该值并使用该值进行 Ajax 调用.响应确定该文本框是红色还是绿色(使用 Jquery css() 函数).

I'm having a quite tough problem and I'm not sure how to approach it. I have a few textboxes in a row and I need to fill in these textboxes. Every time a textbox is filled, I grab the value and make an Ajax call that uses the value. The response determines whether or not that very textbox is colored red or green(using the Jquery css() function).

现在问题来了.假设我连续有 5 个文本框.假设我输入 1-tab、2-tab、2-tab、1-tab、1-tab.所有这一切都非常快.例如,1-tab 表示我键入 1,然后按 Tab 按钮移动到下一个文本框.我意识到如果我走得太快,一些文本框不会更新,它们的颜色也不会改变.我认为这是由于 ajax 需要一些时间来处理.

Now here's the problem. Let's say I have 5 textboxes in a row. Let's say I type 1-tab, 2-tab, 2-tab, 1-tab, 1-tab. All of this very fast. 1-tab, for example, means I type 1 followed by the Tab button to move to the next textbox. I realized that if I go too fast, some of the textboxes don't get updated and their colors do not change. I assumed this is due to the ajax taking some time to process.

我考虑了这个问题,并提出了一个可能解决问题的想法.即在每次 Ajax 调用后添加延迟,然后跳转到下一个.我在 S.O 周围搜索并找到了这个解决方案.但是,它对我来说并没有真正起作用(基本上它坏了并且 JS 根本不起作用).

I thought about the problem and came up with an idea that might solve the problem. That is add a delay after each Ajax call and then tab to the next. I search around S.O and found this solution. However, it's not really working for me(basically it breaks and the JS doesn't work at all).

这是我的 AJAX 的一个片段.我将其剥离并删除了不必要的代码.

$( ".myTextbox" ).keyup(function() {
        //Defining my variables here

        $.ajax({    
            //Perform First Ajax request

            $.ajax({   
                //Perform Second Ajax Request
            });  

        });
});

这是我尝试使用从 S.O 找到的解决方案,但它不起作用.

var timer = null;
$( ".myTextbox" ).keyup(function() {
        clearTimeout(timer);

        timer = setTimeout(
            function(){
                .ajax({    
                //Perform First Ajax request                        
                    $.ajax({   
                        //Perform Second Ajax Request
                    });                  
                });
            }, 200);
        //Defining my variables here
});

现在有两个选项:

  1. 我关于延迟 tab 键的逻辑是错误的.有没有更好的逻辑来克服我最初的问题?

  1. My logic is wrong about delaying the tab key. Could there be some better logic to overcome my initial problem?

我错误地使用了上面发布的解决方案.

I'm using the solution posted above wrongly.

希望得到一些建设性的答案.

Hope to get some constructive answers.

谢谢.

这是完整的代码,应要求提供.

$( ".getqty" ).keyup(function() {
    var split = this.id.split(":");
    var color = split[0];
    var size = split[1];
    var prodID = split[2];
    var $this = $(this);
    var value = $this.val();
    var stock = 0;
    var price = split[3];
    var originalProd = split[4];
    var dataStock = $this.attr("data-stock");
    if(value.length > 0){
        value = parseInt(value);
    }else{
        value = "";
    }

    $.ajax({    //create an ajax request 
        type: 'POST',
        url: 'includes/add.php',             
        dataType: 'html',   //expect html to be returned   
        data:'color='+color+'&size='+size+'&prodID='+prodID+'&qty='+value+'&originalProd='+originalProd+'&dataStock='+dataStock,     
        success: function(response){   
            if(response == "breakOut"){              
                   $this.css('background-color', '#F87171').css('border', '1px solid #B42C2C');  
                   $("#"+originalProd+"-"+color).text("Not enough in stock.").css('color', '#B42C2C');   
                   $("#"+originalProd+"-totalPrice").text("");
            }else{
                stock = response;
                if((value > 0 && value <= stock) || (value > 0 && dataStock == 'yes')){
                        $this.css('background-color', '#66CF66').css('border', '1px solid #277230');                        
                }else{
                    $this.css('background-color', '#fff').css('border', '1px solid #ccc');
                }   

                var count = 0;
                $("."+color+"-" + originalProd).each(function(){
                        if($(this).val() == 0){
                            count = count + 0;
                        }else{
                            count = count + parseFloat($(this).val(), 10);
                        }
                });

                //Single Item Total
                if(count > 0){
                    var totalPrice = (price * count).toFixed(2);
                    $("#"+originalProd+"-"+color).text(count + " - " + totalPrice.toString().replace(/\./g, ',') + " Eur").css('color', '#CCC');
                }else{
                    $("#"+originalProd+"-"+color).text("");
                }


                $.ajax({    //create an ajax request
                    type: 'POST',
                    url: 'includes/cart.php',             
                    dataType: 'html',   //expect html to be returned   
                    success: function(response){                   
                        if(response > 0){
                            $("#cart_price").text("Cart: "+response.toString().replace(/\./g, ',')+ " Eur");
                        }else{
                            $("#cart_price").text("Cart:0,00 Eur");
                        }                            
                    },
                    error:function (xhr, ajaxOptions, thrownError){
                    // alert(thrownError);
                    }
                });  
                if(pathname == 'mycart.php'){
                    location.reload();
                }                  
            }
        },
        error:function (xhr, ajaxOptions, thrownError){
         //alert(thrownError);
        }
    });

推荐答案

您应该使用 change 事件而不是 keyup.来自文档:

You should use the change event instead of keyup. From the docs:

当用户松开按键时,keyup 事件被发送到一个元素键盘.它可以附加到任何元素,但事件只是发送到具有焦点的元素.

The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus.

当您按下 Tab 键时,您的元素将快速改变焦点,并且对于具有正确值内容的输入文本,可能不会触发 keyup 事件.

When you press tab your elements will change focus quickly and maybe the keyup event will not be fired for that input text with the right value content.

那就试试吧:

$( ".getqty" ).change(...)

更新:由于更改事件只会在输入文本失去焦点时触发,因此您可以改为编写:

Update: Since the change event just fires when the input text loses focus, you could write instead:

$( ".getqty" ).on('input', function() {
  var $this = $(this);
  var value = $this.val();

  if (value.length > 0) {
    value = parseInt(value);
  }
  else {
    value = "";
  }

  $.ajax({
    type: 'POST',
    url: 'data.txt',             
    dataType: 'text', 
    success: function(response){   
      $this.css('background-color', '#66CF66').css('border', '1px solid #277230');                        

      $.ajax({
        type: 'POST',
        url: 'data.txt',             
        dataType: 'text', 
        success: function(response){                   
          $("#cart_price").text("Cart: "+response.toString().replace(/\./g, ',')+ " Eur");                          
        },
        error:function (xhr, ajaxOptions, thrownError){
          console.log(thrownError);
        }
      });                 
    },
    error: function (xhr, ajaxOptions, thrownError){
     console.log(thrownError);
    }
  });
});

或者使用纯 javascript 事件侦听器:

Or with pure javascript event listeners:

var elemList = document.getElementsByClassName('getqty');
for (var i = 0; i < elemList.length; i++) {
  elemList[i].addEventListener('input', function(e) {
    var $this = $(e.target);
    var value = $this.val();

    if (value.length > 0) {
      value = parseInt(value);
    }
    else {
      value = "";
    }

    $.ajax({
      type: 'POST',
      url: 'data.txt',             
      dataType: 'text', 
      success: function(response){   
        $this.css('background-color', '#66CF66').css('border', '1px solid #277230');                        

        $.ajax({
          type: 'POST',
          url: 'data.txt',             
          dataType: 'txt', 
          success: function(response){                   
            $("#cart_price").text("Cart: "+response.toString().replace(/\./g, ',')+ " Eur");                          
          },
          error:function (xhr, ajaxOptions, thrownError){
            console.log(thrownError);
          }
        });                 
      },
      error: function (xhr, ajaxOptions, thrownError){
       console.log(thrownError);
      }
    });
  });
}

这篇关于在 Ajax 调用后向 JQuery keyup() 添加延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆