javascript - 如何在无限滚动中清除以前的数据
问题描述
我编写了一个无限卷轴。当用户滚动时,它将加载额外的 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>
解决方案
如果在此之前清空列表,可以吗?
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>
推荐阅读
- php - Laravel - Nexmo 没有在 .ENV 文件中获取凭据
- javascript - 将文本转换为小数字javascript
- angular - RxJS - 条件 Concat 并合并响应中的对象
- javascript - 任意嵌套对象中的递归计数
- java - Java中从头开始的广度优先搜索
- blockchain - 我们如何知道区块链中每个账户的金额?
- reactjs - ECONNREFUSED - 代理来自 React 的 API 请求
- visual-studio-code - VSCode 任务,npm 脚本的用户输入
- ijson - ijson.common.IncompleteJSONError:词法错误:json 文本中的无效字符
- python - 带有 Flask 的 SQLALchemy 中的静态模型实例(夹具)