如何将我网站上的所有 table 标题定义为 JavaScript 中的锚点?

How do I define all table captions on my website as anchors in JavaScript?

我有一个 Jekyll-powered GitHub 页面的网站,我想超链接到我的帖子中我的 table 所在的位置,目前这是我唯一的方法知道如何做到这一点是在 table 之前放置一个标题。这反过来又允许我超链接到 table 之前的标题。例如,https://fusion809.github.io/2015/12/27/comparison-of-free-operating-systems/#programming-languages links to the "Programming Languages" heading in my "A Comparison of Free Operating Systems" post, which is close to, but not immediately before my table entitled "Table 1: A Comparison of Common Programming Languages". Is there a way I can make all table captions (defined with the <caption> tag between <table> and </table> tags) anchors by modifying my website's JavaScript? My table names (or captions) are usually quite long, so if it is possible to use a counter for each, giving them each a number according to their position in my post and then using that for the hyperlink? For example, for the aforementioned post my first table would have the URL https://fusion809.github.io/2015/12/27/comparison-of-free-operating-systems/#table1.

请尝试将您的回答简化为简单的操作,例如我需要添加到我的网站 JavaScript、CSS 或 HTML 的内容,因为我的 programming/markup 知识是在它的婴儿期,因此如果你在深渊中通过我,我会淹死。

您不需要锚点或其他附加标签 -- 文档中的任何 id 都可以通过 http://example.com/mypage#someid

链接到

假设字幕文本是唯一的,您可以遍历每个文本并根据其文本(删除 non-alphanumeric 个字符后)为其赋予 id。我在每个 id 前加上了 "table-" 前缀,并将它们也小写了。

在此示例中,您最终会得到 #table-one#table-two#table-threefour 可用链接:

$('caption').each(
  function() {
    var cap = this;

    var text = $(cap).text();

    // just a-z, 0-9, - and _
    var id = text.replace(/[^a-z0-9\-\_]/g, '').toLowerCase();

    cap.id = "table-" + id;
  }
);
table {
  border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <caption>one</caption>
  <tr>
    <td>td</td>
  </tr>
</table>

<table>
  <caption>Two</caption>
  <tr>
    <td>td</td>
  </tr>
</table>

<table>
  <caption>three four</caption>
  <tr>
    <td>td</td>
  </tr>
</table>

如果字幕 不是 唯一的,您可以使用计数器并只给它们 id s like #table1, #table2,等等

var counter = 0;

$('caption').each(
  function() {
    ++counter;
    this.id = 'table-' + counter;
  }
);