键入单词以CSV格式搜索数据时,为什么搜索框会滞后?

时间:2018-10-12 06:45:50

标签: javascript leaflet openstreetmap

我使用开放的街道地图和传单开发了商店定位器。问题是,当我想在搜索框中输入文字时,它将变得滞后。该商店定位器从具有300 ++数据的CSV文件中读取。以下是搜索框的代码:

var locationLat = [];
var locationLng = [];
var locMarker;
var infoDiv = document.getElementById('storeinfo');
var infoDivInner = document.getElementById('infoDivInner');
var toggleSearch = document.getElementById('searchIcon');
var hasCircle = 0;
var circle = [];
//close store infor when x is clicked
var userLocation;
$("#infoClose").click(function() {
  $("#storeinfo").hide();
  if (map.hasLayer(circle)) {
    map.removeLayer(circle);
  }
});
var listings = document.getElementById('listingDiv');
var stores = L.geoJson().addTo(map);
var storesData = omnivore.csv('assets/data/table_1.csv');

function setActive(el) {
  var siblings = listings.getElementsByTagName('div');
  for (var i = 0; i < siblings.length; i++) {
    siblings[i].className = siblings[i].className
      .replace(/active/, '').replace(/\s\s*$/, '');
  }
  el.className += ' active';
}

function sortGeojson(a,b,prop) {
  return (a.properties.name.toUpperCase() < b.properties.name.toUpperCase()) ? -1 : ((a.properties.name.toUpperCase() > b.properties.name.toUpperCase()) ? 1 : 0);
}

storesData.on('ready', function() {

  var storesSorted = storesData.toGeoJSON();
  //console.log(storesSorted);
  var sorted = (storesSorted.features).sort(sortGeojson)
  //console.log(sorted);
  storesSorted.features = sorted;
  //console.log(storesSorted)
  stores.addData(storesSorted);

  map.fitBounds(stores.getBounds());
  toggleSearch.onclick = function() {
    //var s = document.getElementById('searchbox');
    //if (s.style.display != 'none') {
      //s.style.display = 'yes';
      //toggleSearch.innerHTML = '<i class="fa fa-search"></i>';
      //$("#search-input").val("");

      //search.collapse();
      //document.getElementById('storeinfo').style.display = 'none';
      //$('.item').show();
    //} else {
      //toggleSearch.innerHTML = '<i class="fa fa-times"></i>';
      //s.style.display = 'block';

      //attempt to autofocus search input field when opened
      //$('#search-input').focus();
    //}
  };
  stores.eachLayer(function(layer) {

    //New jquery search
    $('#searchbox').on('change paste keyup', function() {
      var txt = $('#search-input').val();
      $('.item').each(function() {
        if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
          $(this).show();
        } else {
          $(this).hide();
        }
      });
    });

我不知道搜索框中出现延迟的原因是什么。代码或csv文件有问题吗?谢谢

1 个答案:

答案 0 :(得分:0)

每次$('.item').each的迭代都会引起布局的更改,因为$(this).hide()$(this).show()会导致样式被设置为display:none的情况下将该项删除/添加到DOM中来回DOM操作和相应的布局更改非常昂贵。

您可以考虑使用appendChild

累积更改并对DOM进行一次批量更新。