前端随机加载JSON接口数据出现ID重复,如何去重并加载完25条后自动停止
你只需要将原有的前端JS代码替换为以下内容即可实现需求:核心逻辑是预先生成1-25的乱序ID池,每次从池中取ID使用,ID池清空后自动停止所有加载逻辑,不会出现重复ID,25条数据加载完后自动停止加载。
const container = document.getElementById('container'); const loading = document.querySelector('.loading'); // 初始化1-25的ID数组,随机打乱顺序作为待抽取的ID池 const idPool = Array.from({length:25}, (_,i) => i+1).sort(() => Math.random() - 0.5); // 标记所有内容是否加载完成 let isAllLoaded = false; getPost(); getPost(); getPost(); getPost(); window.addEventListener('scroll', () => { // 所有内容加载完成后不再监听滚动加载 if(isAllLoaded) return; const { scrollTop, scrollHeight, clientHeight } = document.documentElement; console.log( { scrollTop, scrollHeight, clientHeight }); if(clientHeight + scrollTop >= scrollHeight - 5) { showLoading(); } }); function showLoading() { // 所有内容加载完成后不再触发加载 if(isAllLoaded) return; loading.classList.add('show'); setTimeout(getPost, 300) } async function getPost() { // 所有内容加载完成后直接返回,不执行请求逻辑 if(isAllLoaded) { loading.classList.remove('show'); return; } const id = getRandomNr(); // 拿不到ID说明已经加载完成,直接返回 if(!id) return; const postResponse = await fetch(`https://example.com/posts/${id}`); const postData = await postResponse.json(); const data = { post: postData}; addDataToDOM(data); console.log(data); } function getRandomNr() { // ID池为空时标记加载完成,返回空 if(idPool.length === 0) { isAllLoaded = true; return null; } // 从ID池末尾取出一个ID返回,不会重复 return idPool.pop(); } function addDataToDOM(data) { const postElement = document.createElement('div'); postElement.classList.add('blog-post'); postElement.innerHTML = ` <h2 class="title">${data.post.title}</h2> <p class="text">${data.post.body}</p> <div class="user-info"> <img src="${data.post.src}" alt="${data.post.title}" /> <span>${data.post.title}</span> </div> `; container.appendChild(postElement); loading.classList.remove('show'); }
替换完成后即可生效,无需修改其他代码。
内容的提问来源于stack exchange,提问作者William V. Davis
相关产品推荐
相关产品推荐

