计算基于用户输入,并且要使用keyup
而不是change
或标准blur
。
问题是代码在每次击键时都会触发,而我需要它延迟并在500ms超时后仅触发一次。我下面的例子显然不起作用,附上小提琴。
我发现了David Walsh的dbounce
功能,但无法弄清楚如何实现它。
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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句