从列表中删除项目(如果存在),然后重新填充列表

时间:2019-01-21 21:59:44

标签: javascript html

我有一些代码在边栏上构建列表的元素。如果单击一个按钮,我想清除列表并用新结果重新填充它。现在,信息仅添加到列表中。我想清除列表中的所有项目,以便阅读。

function buildLocationList(data) {
    for (i = 0; i < data.locations.length; i++) {
      var currentFeature = data.locations[i];
      var prop = currentFeature.locations;


      var listings = document.getElementById('listings');
      var listing = listings.appendChild(document.createElement('div'));

      listing.className = 'item';
      listing.id = "listing-" + i;        

      var link = listing.appendChild(document.createElement('a'));
      link.href = '#';
      link.className = 'title';
      link.dataPosition = i;
      link.innerHTML = '<b>' + currentFeature.company; + '</b>'

      var address = listing.appendChild(document.createElement('div'));
      address.innerHTML = currentFeature.address;

      var csz = listing.appendChild(document.createElement('div'));
      csz.innerHTML = currentFeature.csz;    

      /*var hours = listing.appendChild(document.createElement('div'));
      hours.innerHTML = currentFeature.hours[0].days + ': ' + currentFeature.hours[0].hours;
      hours.style.color = 'gray'; */ 

      link.addEventListener('click', function(e){
        // Update the currentFeature to the store associated with the clicked link
        var clickedListing = data.locations[this.dataPosition];

        // 1. Fly to the point
        flyToStore(clickedListing);

        // 2. Close all other popups and display popup for clicked store
        createPopUp(clickedListing);

        // 3. Highlight listing in sidebar (and remove highlight for all other listings)
        var activeItem = document.getElementsByClassName('active');

        if (activeItem[0]) {
           activeItem[0].classList.remove('active');
        }
        this.parentNode.classList.add('active');

      });
    }
  }

1 个答案:

答案 0 :(得分:1)

对于您的特殊情况,请在执行其他任何操作之前将其添加:

document.getElementById('listings').innerHTML = "";