javascript foreach with DOM



我对JS很陌生,所以很好哈哈,但我正试图使用DOM在页面上创建一个目录。

const h2 = document.querySelectorAll('h2');
const toc = document.querySelector('#toc')
h2.forEach(heading => {
toc.innerHTML = `<li><a href="">${heading}</a></li>`
})

它不像我期望的那样工作。任何帮助都是感激的,我可能只是愚蠢的

我认为这样的东西应该工作!下面是我为使它工作所做的修改:

  • 使用+=代替=为innerHTML。如果您只使用=,每次forEach运行时,它都会替换内容。您正在尝试创建一个列表,所以您希望它添加。
  • heading中获取innerTextheading是一个元素,所以你必须进入它并获取它的文本,否则你显示的内容将不正确。

const h2 = document.querySelectorAll('h2');
const toc = document.querySelector('#toc')
h2.forEach(heading => {
toc.innerHTML += `<li><a href="">${heading.innerText}</a></li>`
})
<ul id="toc"></ul>
<h2>One</h2>
<h2>Two</h2>

关于@Utkarsh Dixit的评论:这是性能更高,并产生相同的结果。

const h2 = document.querySelectorAll('h2');
const toc = document.querySelector('#toc')
h2.forEach(heading => {
// Create two elements
const li = document.createElement('li')
const anchor = document.createElement('a')
// Assign the text content to the anchor
anchor.textContent = heading.textContent
// Add them together toc > li > anchor
li.append(anchor)
toc.append(li)
})
<ul id="toc"></ul>
<h2>One</h2>
<h2>Two</h2>

最新更新