首页 > 解决方案 > 网页上显示新元素时更新数组

问题描述

我正在开发一个 chrome 扩展,我需要在其中收集图书馆中的书籍总数。下面的代码工作正常,但是,我获取数据的页面一次只加载一半的书籍,直到您进一步向下滚动并且数组不会相应更新。有没有办法自动更新数组以跟上变化?

let list = document.querySelectorAll("ul > li");
let numBooks = [];

for (let i = 0; i < list.length; i++) {
  numBooks.push(i + 1);
}

console.log(numBooks);

标签: javascriptarrays

解决方案


// 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,
});

推荐阅读