# 如何在页面渲染完成后运行代码

**URL:** <https://meta.discourse.org/t/how-to-run-code-after-page-has-rendered/358393>\
**Category:** Development\
**Created:** [2025年三月21日 21:49 UTC](https://meta.discourse.org/t/how-to-run-code-after-page-has-rendered/358393 "2025-03-21T21:49:38Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![pfaffman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pfaffman/32/120154_2.png) [@pfaffman](https://meta.discourse.org/u/pfaffman)\
**Post date:** [2025年三月21日 21:49 UTC](https://meta.discourse.org/t/how-to-run-code-after-page-has-rendered/358393/1 "2025-03-21T21:49:38Z")

</div>

我想移除 `span.category-topics--posts-count` 的括号（由 [GitHub - discourse/discourse-right-sidebar-blocks](https://github.com/discourse/discourse-right-sidebar-blocks) 渲染）。我尝试了 `api.onPageChange()` 调用，但它没有获取到任何 countSpans，我认为是因为它运行在另一个主题组件将它们添加到页面之前。

我该怎么办？ 😿

```plaintext

  api.onPageChange(() => {
    console.log("页面已更改");

    const countSpans = document.querySelectorAll(
      "span.category-topics--posts-count"
    );
    console.log("span", countSpans);
    countSpans.forEach((span) => {
      const currentText = span.textContent.trim();
      const newText = currentText.replace(/[()]/g, "");
      span.textContent = newText;
      const number = parseInt(newText);
      if (isNaN(number)) {
        span.style.padding = "0px";
      } else if (number < 10) {
        span.style.padding = "0px";
      } else {
        span.style.padding = "0px 3px";
      }
    });
  });
});

```

---

_[View the full topic](https://meta.discourse.org/t/how-to-run-code-after-page-has-rendered/358393)._
