gpt4 book ai didi

javascript - 拉取标题并以列表格式显示在div中

转载 作者:行者123 更新时间:2023-11-30 23:54:21 24 4
gpt4 key购买 nike

我有一个动态容器 .product_section,我需要以 UL 列表格式将内部标题显示到 div.toc

希望有一个脚本可以检查每个 .product_section 并使用 jquery 创建列表

<div class="toc"></div>    

<div class="product_section">
<h2>Heading 1</h2>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
</div>

<div class="product_section">
<h2>Heading 2</h2>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
</div>

<div class="product_section">
<h2>Heading 3</h2>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
</div>

我怎样才能做到这一点,以便它在每个 .product_section 中创建一个列表

所以就会像这样

<div class="toc">

<ul>
<li><a href="#heading-1">Heading 1</a></li>
<li><a href="#sub-heading">Sub heading</a></li>
<li><a href="#sub-heading">Sub heading</a></li>
<li><a href="#sub-heading">Sub heading</a></li>
</ul>

<ul>
<li><a href="#heading-2">Heading 2</a></li>
<li><a href="#sub-heading">Sub heading</a></li>
<li><a href="#sub-heading">Sub heading</a></li>
<li><a href="#sub-heading">Sub heading</a></li>
</ul>

<ul>
<li><a href="#heading-3">Heading 3</a></li>
<li><a href="#sub-heading">Sub heading</a></li>
<li><a href="#sub-heading">Sub heading</a></li>
<li><a href="#sub-heading">Sub heading</a></li>
</ul>

</div>

最佳答案

您可以尝试以下方法:

//select all the elements with .product_section
var products = document.querySelectorAll('.product_section');
//loop through them
products.forEach(function(el){
//create ul element
var ul = document.createElement('ul');
//find all h2, h3 from the currrent element
var c = el.querySelectorAll('h2, h3');
//loop through them
c.forEach(function(header){
//create li element
var li = document.createElement('li');
//create anchor element
var a = document.createElement('a');
//set the href attribute and set the link text
a.href = '#' + header.textContent.toLowerCase().replace(' ', '-');
a.textContent = header.textContent;
li.appendChild(a);
//append the li to ul element
ul.appendChild(li);
});
//append the ul to div element
document.querySelector('.toc').appendChild(ul);
//remove the current div element
el.remove();
});
<div class="toc"></div>    

<div class="product_section">
<h2>Heading 1</h2>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
</div>

<div class="product_section">
<h2>Heading 2</h2>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
</div>

<div class="product_section">
<h2>Heading 3</h2>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
<h3>Sub heading</h3>
</div>

关于javascript - 拉取标题并以列表格式显示在div中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61166982/

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