如何使用jquery和lodash消除输入的反跳 [英] How to debounce input with jquery and lodash

查看:125
本文介绍了如何使用jquery和lodash消除输入的反跳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您尝试使用jQuery根据输入的值隐藏和显示子级,则在键入时会导致性能问题.为避免在每个字符后都调用过滤器函数,请使用lodashdebounce方法.

If you are trying to hide and show children based on an input's value with jQuery it will cause performance issue while typing. To avoid calling the filter function after every character, use the debounce method of lodash.

html

<input id="search" />

<div>
  <div class="child">foo</div>
  <div class="child">bar</div>
  ....
</div>

javasrcript

  var filterChildren = function() {
    var value = $(this).val().toLowerCase();
    $(".child").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
    });    
  };

  $("#search").on("keyup", _.debounce(filterChildren, 300));

不要错过导入 Lodash jQuery .

PS:这是此帖子答案的一部分:

PS: this is part of the answer of the this post: How to hide the parent div if all its child div are hidden?

推荐答案

$("#search").on("keyup", _.debounce(filterChildren, 300));

function debounce( fn, threshold ) {
    var timeout;
    return function debounced() {
        if ( timeout ) {
            clearTimeout( timeout );
        }
        function delayed() {
            fn();
            timeout = null;
        }
        timeout = setTimeout( delayed, threshold || 100 );
    };
}

这篇关于如何使用jquery和lodash消除输入的反跳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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