将 anchor-able id 动态添加到 HTML headers 的最简单、最安全的方法是什么?

What's the simplest, safest way to dynamically add anchor-able ids to HTML headers?

我想要一个 Tumblr 主题为 post 内容中的每个 header 添加 link-able 锚点。我无权访问或控制该内容的呈现; Tumblr 倾向于吐出普通的 <h2>s 和类似的,对于 Markdown headers:

## Hello,  friend !        ->       <h2>Hello,  friend !</h2>

我想确保 post 的任何部分都可以直接超链接到 anchor link,例如 http://thing.place/post/12345#hello-friend。有没有人有一个简单、相当通用的 JavaScript 片段来清理任何 header 元素的内容,并将其作为 id 添加到 header?

(大概,如果您已经为自己编写了此代码;您可能还需要一些额外的代码来添加一个 anchor-link 指示符 self-links;如果您有,请分享它知道了。)

我有一个非常幼稚的解决方案,它取决于 jQuery and Lodash (and I do mean full jQuery, as Zepto and friends don't include :header);但轻量级、优雅、纯粹的 JavaScript 解决方案是首选:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<script>
   jQuery.noConflict(true)(function($){
      var lodash = _.noConflict()
        , anchor = "\u2693\uFE0E"

      $(':header')
      .wrap(function(){
         var wrapper = document.createElement('header')
           ,   title = lodash.kebabCase( $(this).text() )

         return $(wrapper).attr('id', title) })
   })
</script>

这会添加额外的语义 <header> 元素,我打算将其用于其他目的,但这可能不是必需的。

我维护了一个项目来完成您所描述的:AnchorJS

包含脚本后,您可以使用选择器选择要添加锚点的元素:

// Add anchors to all h1's and h2's on the page
anchors.add('h1, h2');

它对 Jquery 或 Lodash 没有任何依赖性,以防 Tumblr 出现问题(我对 Tumblr 不够熟悉,不知道那里的限制)。