当鼠标(或手指)不再拖动时,我怎么能只在更改时运行AJAX调用呢

How can I only run an AJAX call on change when the mouse (or finger) is no longer dragging?

本文关键字:运行 调用 AJAX 怎么能 鼠标 手指 拖动 不再      更新时间:2023-09-26

我有一系列交互式滑块,可以更改计算值。

计算在拖动手柄的每一个微小移动上运行(通过鼠标向下或触摸拖动事件)。

我需要用值更新数据库,但我更希望只在用户"放下"句柄后获取值。

如何确定手指或鼠标是否按下,以便跳过AJAX调用?

function handleIsBeingDragged() {
    // calculations based on all the input values here
    // pseudo-code to check for mouseup event
    if (mouseUp) {
        // save only if mouse is now up - to avoid hundreds of updates per drag event
        $.ajax();
    }
}

您需要在代码中添加一些滞后。

碰巧我为SO上的另一个答案写了一个通用的debounce函数,这对这很有用。

以下是使用方法:

function saveTheData() {
    $.ajax(); ///
}
var saveTheDataDebounced = debounce(50, saveTheData);
function handleIsBeingDragged() {
    saveTheDataDebounced();
}

debounce功能:

// debounce - debounces a function call
//
// Usage: var f = debounce([guardTime, ] func);
//
// Where `guardTime` is the interval during which to suppress
// repeated calls, and `func` in the function to call.
// You use the returned function instead of `func` to get
// debouncing;
//
// Example: Debouncing a jQuery `click` event so if it happens
// more than once within a second (1,000ms), subsequent ones
// are ignored:
//
//    $("selector").on("click", debounce(1000, function(e) {
//      // Click occurred, but not within 1000ms of previous
//    });
//
// Both `this` and arguments are passed through.
function debounce(guardTime, func) {
  var last = 0;
  if (typeof guardTime === "function") {
    func = guardTime;
    guardTime = 100;
  }
  if (!guardTime) {
    throw "No function given to debounce";
  }
  if (!func) {
    throw "No func given to debounce";
  }
  return function() {
    var now = +new Date();
    if (!last || (now - last) > guardTime) {
      last = now;
      return func.apply(this, arguments);
    }
  };
}

您可以将AJAX调用分配给"mouseup"事件。在jQuery mobile"vmouseup"中。