【发布时间】:2020-03-30 08:22:37
【问题描述】:
嘿,
我有一个 javascript 函数来获取当前页面上的所有 '' 项目。这可以正常工作,但我想使用输出名称作为每个 li 项目的链接。这里举个例子:
其中一个 li 项目的名称为:'Scalder'。它看起来像这样:
<ul>
<li>Scalder</li>
<li>other-item</li>
<li>other-item</li>
<li>other-item</li>
</ul>
我想得到这样的结果:
<ul>
<li id='Scalder'>Scalder</li>
<li id='other-item'>other-item</li>
<li id='other-item'>other-item</li>
<li id='other-item'>other-item</li>
</ul>
每个项目还必须设置li-item的链接。
我当前的构建代码是:
var mainEl = document.getElementsByTagName("main"),
//Because we only have one main tag, from the previous
//collection we chose the first elemnt
//From that element we create a collection with all the h2 inside
headingsEls = mainEl[0].getElementsByTagName("output"),
//collection of elements with "aside" tag
asideEl = document.getElementsByTagName("aside"),
//We create the ul that wil hold the list
ulEl = document.createElement("ul")
//Go throw the h2 collection and for each element we create a new li element,
//we pass to it the text content and we put it on the ul
for( var i = 0; i < headingsEls.length; i++ ) {
var liEl = document.createElement("li")
liEl.textContent = headingsEls[i].textContent
ulEl.appendChild(liEl)
}
//the new ul with the list is appended!
asideEl[0].appendChild(ulEl)
希望我清楚我的愿望。祝你有美好的一天!
【问题讨论】:
-
所以你想设置每个
li的id来匹配它的文本?请注意,您可能很容易在此处出现重复,并且文本中的任何空格都将意味着id无效。不过,我会问你为什么觉得有必要这样做,因为在运行时设置 id 是一种小代码气味。
标签: javascript jquery html hyperlink