gpt4 book ai didi

javascript - 使用 jQuery 将 header (

--

标签)解析为有序列表?
转载 作者:搜寻专家 更新时间:2023-11-01 04:26:01 24 4
gpt4 key购买 nike

我正在根据标题结构以有序列表的样式制作目录,这样:

<h1>lorem</h1>
<h2>ipsum</h2>
<h2>dolor</h2>
<h3>sit</h3>
<h2>amet</h2>

变成:

  • 洛伦
    • 假设
    • 多尔
      • 坐下
    • 阿梅特

这就是我目前的做法:

$('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()

哪个有效,但它似乎缺乏优雅。有没有更智能/更快/更强大的方法来做到这一点?

最佳答案

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;
});

也许有人会派上用场))

关于javascript - 使用 jQuery 将 header (<h1> -- <h6> 标签)解析为有序列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17419747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com