【问题标题】:How to debounce input with jquery and lodash如何使用 jquery 和 lodash 去抖动输入
【发布时间】:2019-01-21 02:21:55
【问题描述】:

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

html

<input id="search" />

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

java脚本

  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));

不要错过导入LodashjQuery

PS:这是这篇文章的答案的一部分: How to hide the parent div if all its child div are hidden?

【问题讨论】:

    标签: javascript jquery lodash


    【解决方案1】:

    我提出了另一种没有 lodash 的解决方案。只需在页面加载时使用您的元素创建地图(假设它们不会更改并且仅在页面加载时创建一次)。

    $(document).ready(function(){
      var map = {};
      $('.child').each(function(i,el){
        map[$(el).text().toLowerCase()] = $(el);
      });
      $('.child').toggle(false);
      $('#search').on('keyup', function(){
        $('.child').toggle(false);
        var el = map[$(this).val().toLowerCase()];
        if (el)
          $(el).toggle(true);
      });
    });
    

    Live preview

    【讨论】:

      【解决方案2】:
      $("#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 );
          };
      }
      

      【讨论】:

        猜你喜欢
        • 2016-07-17
        • 2021-07-16
        • 2020-06-24
        • 2017-05-03
        • 2015-05-21
        • 2021-11-27
        • 2013-03-10
        • 2017-07-08
        • 1970-01-01
        相关资源
        最近更新 更多