【问题标题】:Create list with hyperlink (document fragments) as text string使用超链接(文档片段)作为文本字符串创建列表
【发布时间】:2021-12-07 12:57:56
【问题描述】:
我是 javascript 的新手,我正在尝试在 JavaScript 中创建一个动态列表,它既是一个超链接,又是在我的 html 代码中显示 id = v1 的标签的文本字符串。有点像同一网页不同部分的菜单。
我曾尝试使用文档片段 (https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks#document_fragments) 执行此操作,但它不起作用,我不知道如何在“菜单”中插入文本字符串。
这是我的代码的一部分:
var container = document.getElementById("contentarea");
var header = document.getElementById("v1");
for (i = 0; i < length.header; i++) {
$(document.createElement("li")).li;
$(document.createElement("a")).link.append(li)( {
href: "#v1"
})
list.appendChild(li);
container.appendChild(list)
}
【问题讨论】:
标签:
javascript
jquery
list
【解决方案1】:
你可以这样做
// div to get the textContent from, replace it with whatever you want
const divE = document.getElementById('test');
// our list tag
const list = document.getElementById('list');
// looping
for (let i = 0; i < 4; i++) {
const listEl = document.createElement('li'); // our list element
const aTag = document.createElement('a'); // a new <a> tag to append link
const linkTag = document.createElement('link'); //new link tag
linkTag.href = '#test'; // setting hyperlink
aTag.textContent = divE.textContent // setting the textContent for <a> tag
aTag.appendChild(linkTag); // appending link to the a tag
listEl.appendChild(aTag); // appending a tag to the <li> tag
list.appendChild(listEl) // finally appending our list element to the main list
}
<div id="test">Something here</div>
<ul id="list"></ul>