使用$ .each限制实时搜索json数据中的行数

时间:2019-04-29 08:28:51

标签: javascript php jquery json ajax

我试图限制通过URL在实时搜索JSON数据中获得的行数,我尝试不计算表行数并返回false,但它不起作用,有任何方法可以实现。

$(document).ready(function() {
      $.ajaxSetup({
        cache: true
      });
      $('#search').keyup(function() {
        $('#result').html('');
        $('#state').val('');
        var searchField = $('#search').val();
        var expression = new RegExp(searchField, "i");
        $.getJSON('https://vast-shore-74260.herokuapp.com/banks? 
          city = MUMBAI ', function(data) {
          $.each(data, function(key, value) {
              var count = 0;

              if ((value.city.search(expression) != -1 ||
                  value.branch.search(expression) != -1) && count < 10) {
                $('#result').append('<tr><th>' + value.bank_name + '</th>' +
                  '<th>' + value.address + '</th>' +
                  '<th>' + value.ifsc + '</th>' +
                  '<th>' + value.branch + '</th>' +
                  '<th>' + value.bank_id + '</th></tr>'
                  count++;
                }
                else {
                  return false;
                }
              });
          });
      });

1 个答案:

答案 0 :(得分:0)

尝试一下-至少将count = 0移出循环

$(document).ready(function() {
  $.ajaxSetup({
    cache: true
  });
  $('#search').keyup(function() {
    $('#result').html('');
    $('#state').val('');
    var searchField = $('#search').val();
    var expression = new RegExp(searchField, "i");
    $.getJSON('https://vast-shore-74260.herokuapp.com/banks?city=MUMBAI', function(data) {
      var count = 0;
      $.each(data, function(key, value) {
        if (count >= 10) return false;
        if (value.bank_name.search(expression) != -1) {
          $('#result').append('<tr><th>' + value.bank_name + '</th>' + '<th>' + value.bank_id + '</th></tr>');
          count++;
        }
      });
    });
  });
});