Parse header (lt;h1gt; -- lt;h6gt; tags) to ordered list, using jQuery?(使用jQuery将标题(lt;h1gt;--lt;h6gt;标签)解析为有序列表?)
问题描述
我正在根据标题结构以有序列表的样式制作目录,这样:
I'm making a table of contents, in the style of an ordered list, based on the header structure, such that:
<h1>lorem</h1>
<h2>ipsum</h2>
<h2>dolor</h2>
<h3>sit</h3>
<h2>amet</h2>
变成:
- 洛雷姆
- ipsum
- 朵儿
- 坐下
这就是我目前的做法:
$('h1, h2, h3, h4, h5, h6').each ()-> # get depth from tag name depth = +@nodeName[1] $el = $("<li>").text($(this).text()) do get_recursive_depth = ()-> if depth is current_depth $list.append $el else if depth > current_depth $list.append( $("<ol>") ) unless $list.children().last().is('ol') $list = $list.children().last() current_depth += 1 get_recursive_depth() else if depth < current_depth $list = $list.parent() current_depth -=1 get_recursive_depth()
哪个有效,但它似乎缺乏优雅.有没有更智能/更快/更健壮的方法来做到这一点?
which works, but it seems like it lacks elegance. Is there a smarter / faster / more robust way to do this?
推荐答案
jQuery 实现:
var $el, $list, $parent, last_depth; $list = $('ol.result'); $parent = []; $parent[1] = $list; last_depth = 1; $el = 0; $('h1, h2, h3, h4, h5, h6').each(function () { var depth; depth = +this.nodeName[1]; if (depth > last_depth) { $parent[depth] = $('<ol>').appendTo($el); } $el = $("<li>").text($(this).text()); $parent[depth].append($el); return last_depth = depth; });
也许有人会派上用场))
Maybe someone will come in handy))
这篇关于使用jQuery将标题(<h1>--<h6>标签)解析为有序列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用jQuery将标题(<h1>--<h6>标签)解析为有序列表?


基础教程推荐
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 响应更改 div 大小保持纵横比 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01