如何将debounce fn实现到jQuery keyup事件中? [英] How to implement debounce fn into jQuery keyup event?

查看:208
本文介绍了如何将debounce fn实现到jQuery keyup事件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

计算基于用户输入,标准是使用 keyup 而不是更改模糊

A calculation is based on user input, and criteria is to use keyup rather than change or blur.

问题是代码会在每次击键时触发,我需要它才能延迟和触发一次500毫秒超时。我下面的例子显然不起作用,小提琴附件。

The problem is that the code fires on every keystroke, and I need it to delay and fire only once after a 500ms timeout. My example below obviously doesn't work, fiddle attached.

我发现David Walsh的 dbounce 函数,但无法计算如何实施它。

I found David Walsh's dbounce function, but cannot figure out how to implement it.

jsFiddle

HTML:

<input type="text" />
<input type="text" id="n2" class="num" value="17" disabled />
<input type="text" id="n3" class="num" value="32" disabled />

javascript / jQuery:

$('input').keyup(function(){
    var $this=$(this);
    setTimeout(function(){
        var n1 = $this.val();
        var n2 = $('#n2').val();
        var n3 = $('#n3').val();
        var calc = n1 * n2 * n3;
        alert(calc);
    },500);
});

//http://davidwalsh.name/javascript-debounce-function
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};


推荐答案

像这样使用: -

$('input').keyup(debounce(function(){
        var $this=$(this);
        //alert( $this.val() );
        var n1 = $this.val();
        var n2 = $('#n2').val();
        var n3 = $('#n3').val();
        var calc = n1 * n2 * n3;
        alert(calc);
    },500));

小提琴

这篇关于如何将debounce fn实现到jQuery keyup事件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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