gpt4 book ai didi

javascript - 从列表项文本生成 href

转载 作者:行者123 更新时间:2023-11-27 23:27:00 25 4
gpt4 key购买 nike

更新:

我有一个侧边栏,它提取所有现有的 h3 标签并在列表中显示文本。我希望这些列表项具有与文本相同的 id 和 href。

示例列表项:

当前:<li>Heading One</li>

需要:<li id="heading-one"><a href="#heading-one">Heading One</li>

HTML:


<div id="content">
<h3 id="example-one">Example One</h3>
<h3 id="example-two">Example Two</h3>
<h3 id="example-three">Example Three</h3>
</div>

<div id="sidemenu-container">
<div class="wpb_wrapper">
<div class="wpb_wrapper">
</div>
</div>
</div>


JavaScript:


jQuery(function($) {
$(document).ready(function(){

// Create array from h3s found in main content
let nodeList = document.getElementById('content').querySelectorAll('h3');
let list = [];
nodeList.forEach(function(val){
list.push(val.innerHTML)
})

// Create unordered list
var ul = document.createElement('ul');

// Append unordered list to sidebar
document.getElementById('sidemenu-container').getElementsByClassName("wpb_wrapper")[1].appendChild(ul).id = "top-menu";

// Append list items to unordered list
list.forEach(function(title){
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML += title;
});

});
});

期望的结果:


<div id="content">
<h3 id="example-one">Example One</h3>
<h3 id="example-two">Example Two</h3>
<h3 id="example-three">Example Three</h3>
</div>

<div id="sidemenu-container">
<div class="wpb_wrapper">
<ul>
<li><a href="#example-one">Example One</a></li>
<li><a href="#example-two">Example Two</a></li>
<li><a href="#example-three">Example Three</a></li>
</ul>
</div>
</div>

JSFiddle:

https://codepen.io/Crawlinson/pen/OJLjyGe

最佳答案

jQuery(function($) {
$(document).ready(function(){

// Create array from h3s found in main content
let nodeList = document.getElementById('content').querySelectorAll('h3');
let list = [];
nodeList.forEach(function(val){
list.push(val.innerHTML)
})

// Create unordered list
var ul = document.createElement('ul');

// Append unordered list to sidebar
document.getElementById('sidemenu-container').getElementsByClassName("wpb_wrapper")[1].appendChild(ul).id = "top-menu";

// Append list items to unordered list
list.forEach(function(title){
var li = document.createElement('li');
var a = document.createElement('a');
var id = title.toLowerCase().split(" ").join('-');
ul.appendChild(li);
a.href = "#" + id;
li.id = id

a.innerHTML += title;
li.appendChild(a);
});

});
});

关于javascript - 从列表项文本生成 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57726137/

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