# 页脚的 Javascript 在页面转换后无法正常工作

**URL:** https://meta.discourse.org/t/javascripts-targeting-the-footer-doesnt-work-after-page-transitions/180012
**Category:** Development
**Created:** [2021年二月17日 11:16 UTC](https://meta.discourse.org/t/javascripts-targeting-the-footer-doesnt-work-after-page-transitions/180012 "2021-02-17T11:16:39Z")
**Posts on this page:** 1
**Showing post:** 4

<div class="post-metadata">

### Author: ![Johani](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/johani/32/176920_2.png) [@Johani](https://meta.discourse.org/u/Johani)
#### Post date: [2021年二月19日 06:13 UTC](https://meta.discourse.org/t/javascripts-targeting-the-footer-doesnt-work-after-page-transitions/180012/4 "2021-02-19T06:13:17Z")

</div>

解决这个问题可能有几种方法，但让我们尝试使用正确的自定义钩子来“规范”地处理。

当你向主题的页脚部分添加 HTML 时，Discourse 会进行一些处理，以防止其在页面切换或无限滚动添加更多元素时出现跳动。

它会被添加为一个 `custom-html` 组件，位置如下：

[discourse/app/assets/javascripts/discourse/app/templates/application.hbs at a0bbc346cb5d5b89d1a3efdfa89869349a8b067f · discourse/discourse · GitHub](https://github.com/discourse/discourse/blob/a0bbc346cb5d5b89d1a3efdfa89869349a8b067f/app/assets/javascripts/discourse/app/templates/application.hbs#L31)

如果你查看该组件的代码，会发现它在渲染时会触发一个应用事件。

[discourse/app/assets/javascripts/discourse/app/components/custom-html.js at a0bbc346cb5d5b89d1a3efdfa89869349a8b067f · discourse/discourse · GitHub](https://github.com/discourse/discourse/blob/a0bbc346cb5d5b89d1a3efdfa89869349a8b067f/app/assets/javascripts/discourse/app/components/custom-html.js#L24-L29)

这就是你需要使用的钩子。

如何使用它？  
[plugin-api](https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/app/lib/plugin-api.js) 中有一个方法，允许你在特定应用事件触发时执行代码。

[https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/app/lib/plugin-api.js#L507-L519](https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/app/lib/plugin-api.js#L507-L519)

既然我们已经知道事件名称，就可以这样使用：

```javascript
api.onAppEvent("inserted-custom-html:footer", () => {
  // 在此处执行你的操作
});

```

由于这是一个 plugin-API 方法，你需要将脚本标签的类型更改为 `text/discourse-plugin`，如下所示：

```xml
<script type="text/discourse-plugin" version="0.8">
api.onAppEvent("inserted-custom-html:footer", () => {
  // 在此处执行你的操作
});
</script>

```

上面的代码片段会在页脚渲染时触发。因此，你现在可以这样做：

```xml
<script type="text/discourse-plugin" version="0.8">
api.onAppEvent("inserted-custom-html:footer", () => {
  $(".footer-div #footerNavDiv").click(function () {
    console.log("click event captured");
    // 在此处处理点击事件的操作
  });
});
</script>

```

你可以在此处了解更多关于 plugin-API 的信息：[这里](https://meta.discourse.org/t/developer-s-guide-to-discourse-themes/93648#heading--4-c)

---

_[View the full topic](https://meta.discourse.org/t/javascripts-targeting-the-footer-doesnt-work-after-page-transitions/180012)._
