每次我一次加载所有内容时,都会出现数千个对象和 chrome 崩溃。
btn.addEventListener('click', function(){
event.preventDefault();
async function getData(){
const response=await fetch(url)
const data= await response.json();
info(data)
}
getData();
function info(x){
x.messages.forEach(element => {
console.log(element.creator.name+": "+element.text)
// console.log(x.element.text)
con.innerHTML += "<p>"+element.creator.name+": "+element.text+"</p>";
});
}
这是我使用 rn 的代码
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
第一个innerhtml因为每次都要解析所以很慢。创建一个函数来创建 Dom 元素并将其附加到所需的容器。添加分页或流程以按块插入数据也会有所帮助。
尝试使用附加子元素每次加载一个元素。 我在这里留下了一个替代代码。
沙箱
代码
const btn = document.getElementById("BtnInfo"); btn.addEventListener("click", function (event) { event.preventDefault(); async function getData() { const response = await fetch("https://dummyjson.com/products/1"); const data = await response.json(); info(data); } getData(); function info(x) { for (let key in x) { var pElement = document.createElement("p"); pElement.textContent = `${key}: ${x[key]}`; document.body.appendChild(pElement); } } });