Как очистить предыдущие данные в бесконечной прокрутке - PullRequest
2 голосов
/ 14 апреля 2020

Я закодировал бесконечный свиток. Когда пользователь выполняет прокрутку, он загружает дополнительные 20 элементов, что делает его длинным списком.

Я хочу, чтобы свиток загружал новые элементы и очищал предыдущие элементы.

var listElm = document.querySelector('#infinite-list');

// Add 20 items.
var nextItem = 1;
var loadMore = function() {
  for (var i = 0; i < 20; i++) {
    var item = document.createElement('li');
    item.innerText = 'Item ' + nextItem++;
    listElm.appendChild(item);
  }
}

// Detect when scrolled to bottom.
listElm.addEventListener('scroll', function() {
  if (listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) {
    loadMore();
  }
});

// Initially load some items.
loadMore();
#infinite-list {
  /* We need to limit the height and show a scrollbar */
  width: 200px;
  height: 300px;
  overflow: auto;

  /* Optional, only to check that it works with margin/padding */
  margin: 30px;
  padding: 20px;
  border: 10px solid black;
}

/* Optional eye candy below: */
li {
  padding: 10px;
  list-style-type: none;
}
li:hover {
  background: #ccc;
}
<ul id='infinite-list'>
</ul>

Ответы [ 2 ]

0 голосов
/ 14 апреля 2020

Вы можете очищать список каждый раз, когда вызывается loadMore ().

var listElm = document.querySelector('#infinite-list');

// Add 20 items.
var nextItem = 1;
var loadMore = function() {
  //Here we empty the list to remove the old results
  listElm.innerHTML = ''
  //And then load the new items
  for (var i = 0; i < 20; i++) {
    var item = document.createElement('li');
    item.innerText = 'Item ' + nextItem++;
    listElm.appendChild(item);
  }
}

// Detect when scrolled to bottom.
listElm.addEventListener('scroll', function() {
  if (listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight ) {
    loadMore();
  }
});

// Initially load some items.
loadMore();
0 голосов
/ 14 апреля 2020

Если вы очистите список до этого, все будет в порядке?

var listElm = document.querySelector('#infinite-list');

// Add 20 items.
var nextItem = 1;
var loadMore = function() {
  listElm.innerHTML = ''
  for (var i = 0; i < 20; i++) {
    var item = document.createElement('li');
    item.innerText = 'Item ' + nextItem++;
    listElm.appendChild(item);
  }
}

// Detect when scrolled to bottom.
listElm.addEventListener('scroll', function() {
  if (listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight ) {
    loadMore();
  }
});

// Initially load some items.
loadMore();
#infinite-list {
  /* We need to limit the height and show a scrollbar */
  width: 200px;
  height: 300px;
  overflow: auto;

  /* Optional, only to check that it works with margin/padding */
  margin: 30px;
  padding: 20px;
  border: 10px solid black;
}

/* Optional eye candy below: */
li {
  padding: 10px;
  list-style-type: none;
}
li:hover {
  background: #ccc;
}
<ul id='infinite-list'>
</ul>
...