javascript - 网页上显示新元素时更新数组
问题描述
我正在开发一个 chrome 扩展,我需要在其中收集图书馆中的书籍总数。下面的代码工作正常,但是,我获取数据的页面一次只加载一半的书籍,直到您进一步向下滚动并且数组不会相应更新。有没有办法自动更新数组以跟上变化?
let list = document.querySelectorAll("ul > li");
let numBooks = [];
for (let i = 0; i < list.length; i++) {
numBooks.push(i + 1);
}
console.log(numBooks);
解决方案
// Variables
let list = document.querySelectorAll("ul > li");
let mlist = document.querySelector("ul");
let numBooks = [];
// Push books to array
for (let i = 0; i < list.length; i++) {
numBooks.push(i + 1);
}
// Observe changes
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.addedNodes.length) {
// Create Element: Book Count
let url = "myurl";
let nBooks = numBooks.length / 10;
let nChanges = mutation.addedNodes.length - 1;
if (url == window.location.href) {
let el = document.createElement("span");
el.innerHTML = nBooks + nChanges;
let par = document.getElementsByTagName("h2")[0];
par.appendChild(el);
}
}
});
});
observer.observe(mlist, {
childList: true,
});
推荐阅读
- python - 具有最小纠错的两个序列之间的最长公共子串
- oracle - Oracle Apex 计数器显示新行
- flutter - 使用 BottomNavigationBar 在屏幕之间切换时,Flutter 中出现“'!_needsLayout': is not true”错误
- r - 如何使用代码在 R Shiny 中触发 session$onSessionEnded?
- wordpress - 我的 wordpress 网站已关闭,如何解决此错误
- android - 读取发布者账号配置失败;请检查您配置的应用 ID。收到的应用 ID:`ca-app-pub-3940256099942544~3347511713`
- javascript - document.querySelectorAll.forEach 奇怪的行为
- c++ - 在返回内存的 DLL 函数中,在哪里分配和在哪里释放?
- android - FCM 注册期间出错。请设置您的项目ID
- asp.net-core - 错误 CS0234 在 asp.net 核心的命名空间“System.Web”中不存在类型或命名空间名称“HttpContext”