【问题标题】:Is there any way to know if a button is not clicked a determined time?有没有办法知道一个按钮是否在确定的时间没有被点击?
【发布时间】:2013-03-01 13:03:55
【问题描述】:

有什么方法可以知道按钮是否在确定的时间没有被点击? 我有两个递增和递减按钮(加号和减号)来通过 Ajax 请求控制温度。该值与 next 函数一一递增:

Plugin_increment.prototype.startPluginTempe = function (selector, dataAux, dataAux2, varAux, varAux2) {
    var valueElement = $(selector);
    function incrementValue(e){
        if((valueElement.text() < 40) && (valueElement.text() > 10)){ //max and min
            valueElement.text(Math.max(parseInt(valueElement.text()) + e.data.increment)); 
        }

        if(valueElement.text() == 40){//max
            if(e.data.increment == -1){
                valueElement.text(Math.max(parseInt(valueElement.text()) + e.data.increment));
            }
        }
        if(valueElement.text() == 10){//min
            if(e.data.increment == 1){
                    valueElement.text(Math.max(parseInt(valueElement.text()) + e.data.increment));                  
                }   
        }
        //Ajax request??????
        return false;
    }
    $(varAux).button({
              icons: {
                 primary: "ui-icon-plusthick"
              },
              text: false
        }).bind('click', {increment: 1}, incrementValue);       
    $(varAux2).button({
              icons: {
                 primary: "ui-icon-minusthick"
              },
              text: false
        }).bind('click', {increment: -1}, incrementValue);

};

"selector" 是显示值的 span 的选择器。 "varAux" 和 "varAux2" 是加号和减号按钮的选择器。

如果我为每个增量发送一个 Ajax 请求,客户端就会超载。我认为一个选项可能是知道一个按钮是否在确定的时间没有被点击。另一种方式?

我使用 jquery-ui 来加减按钮。

【问题讨论】:

  • 为什么不禁用按钮,直到 ajax 请求完成?
  • 因为增量是一对一的,如果我想增加五个单位的值。将有五个 Ajax 请求。会有不必要的要求

标签: javascript jquery


【解决方案1】:

您可以在 AJAX 请求之间设置一个最小间隔。如果在该时间间隔内点击了两次按钮,则只会执行一次请求,如下所示:

function incrementValue(e) {
    //your existing code here
    scheduleAjaxRequest();
}

var minimumTimeBetweenAjaxRequests = 500; // in milliseconds
var ajaxRequestIsScheduled;

function scheduleAjaxRequest() {
    if (ajaxRequestIsScheduled) {  
        // two or more clicks within specified interval, 
        // the data will be sent in request that's already sceheduled
        return;
    }
    ajaxRequestIsScheduled = setTimeout(doAjaxRequest, minimumTimeBetweenAjaxRequests);
}

function doAjaxRequest() {
    //Ajax request
    ajaxRequestIsScheduled = null; // clear timeout ID to allow next request to be scheduled
}

【讨论】:

  • 这种方法的一个潜在问题是,如果 AJAX 请求由于某种原因失败,客户端数据和服务器端数据将不同步。所以你应该考虑适当地处理 AJAX 错误
  • 是个好主意,但我更愿意在多次点击停止时只实现一个请求。最终目的是减少 Ajax 请求,而不是延迟它们。会有不必要的要求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 2021-05-01
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
相关资源
最近更新 更多