JQuery延迟键盘搜索

时间:2016-10-21 10:39:20

标签: jquery

我有这个代码来隐藏除了我搜索的那个元素之外的每个.flip元素:

var $rows = $('.flip'); 
$('#search').keyup(function() 
{
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();  
    $rows.show().filter(function()                                      
    {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
    }).hide();  
}); 

这个问题在于每次我发布密钥时都会搜索。如何让它等到我停止输入

谢谢!

2 个答案:

答案 0 :(得分:2)

只需使用 <ProgressBar android:progressDrawable="@drawable/green_progress_drawable" style="?android:attr/progressBarStyleHorizontal" android:id="@+id/mf_progress_bar" app:layout_widthPercent="80%" app:layout_heightPercent="8%" app:layout_marginTopPercent="5%" android:layout_gravity="center_horizontal" />

即可

setTimeout
$(document).ready(function() {
  var timer;

  var $rows = $('.flip');
  var $self = $(this);

  $('#search').keyup(function() {
    clearTimeout(timer);

    timer = setTimeout(function() {
      $('#test').text(Math.floor(Math.random() * 1000));
      var val = $.trim($self.val()).replace(/ +/g, ' ').toLowerCase();

      $rows.show().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
      }).hide();
    }, 300);
  });
})

答案 1 :(得分:1)

你需要使用去抖动,我建议使用lodash

我这样用:

var debounce = _.debounce(search, 500, false);

$('#search-input').on('change', function() {
  debounce(this);
});

function search(input) {
  if(input.value.length > 2) {
    ...
  }
}

_.debounce将完成等待用户停止插入值的工作。

第一个参数是等待用户停止插入值后要调用的函数。

第二个参数是等待下一个值插入的时间(以毫秒为单位)。

第三个参数是配置选项,使用false会使它发送最后插入的值。

相关问题