当鼠标(或手指)不再拖动时,我怎么能只在更改时运行AJAX调用呢
How can I only run an AJAX call on change when the mouse (or finger) is no longer dragging?
我有一系列交互式滑块,可以更改计算值。
计算在拖动手柄的每一个微小移动上运行(通过鼠标向下或触摸拖动事件)。
我需要用值更新数据库,但我更希望只在用户"放下"句柄后获取值。
如何确定手指或鼠标是否按下,以便跳过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"中。
相关文章:
- 运行Infinite Scroll后调用函数时出现问题
- 重新运行上次进行的AJAX调用
- For循环在调用时未运行
- AJAX调用运行C代码的最佳实践
- HTML5(Bootstrap)通过函数调用运行动画
- 在jquery中完成ajax调用后,如何运行一些代码
- 防止函数在从ajax再次调用后多次运行
- 如何显示由ajax调用运行的PHP文件的echo
- Ajax调用在InternetExplorer中冻结UI,但在firefox中运行良好
- 通过Wordpress中的jquery调用运行php文件
- JavaScript只有在最后一次被调用时才运行函数
- 在异步AJAX调用完成后,通过变量运行函数
- 如何从 MVC4 链接调用 Javascript 方法(错误 JavaScript 运行时错误:对象不支持此操作)
- 运行一次函数,然后在 5 秒内禁止进一步调用
- 运行 AJAX 需要什么 - 将 jQuery 添加到页面处理 AJAX 调用
- 从 jquery.ready() 调用的 javascript 何时相对于 中的脚本运行
- 如何使用仅在运行时已知的变量名称调用 JavaScript 函数
- 如何运行一个调用某个函数的函数首先完成它,然后再调用下一个函数.正在创建回调函数
- 动态弹出窗口'通过调用一个永远运行并返回's每个周期后的数据
- 如何从 html 文件运行/调用 javascript 文件中的 javascript 函数