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

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

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

我需要使用值更新数据库,但是只想在用户“删除”句柄后获取值。

如何确定手指或鼠标是否已关闭,以便跳过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(); } 

debouncefunction:

 // 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”中。