如何解决为什么列表未显示在页面上
我尝试创建一个列表,并使用js将href
动态添加到我的li
中,但我无法在页面上看到我的元素(只有当我使用F12时,我才能看到带有正确的数据),我缺少什么?
这是我的代码:
js:
function createListOfFiles(names,hrefs) {
let output = document.getElementById("listing"); //list elemenst
for (let j = 0; names.length > j; j++) {
var li = document.createElement('li');
li.style.display = "inline";
var ahref = document.createElement('a');
ahref.setAttribute('href',hrefs[j]);
ahref.setAttribute('textContent',names[j]);
li.appendChild(ahref);
output.appendChild(li);
}
}
html:
<ul id="listing" style="list-style-type:none;background-color:blue;font-size:120%;"></ul>
解决方法
function createListOfFiles(names,hrefs) {
const output = document.getElementById("listing");
for (let j = 0; names.length > j; j++) {
const li = document.createElement('li');
const ahref = document.createElement('a');
li.style.display = "inline";
ahref.setAttribute('href',hrefs[j]);
ahref.innerText = names[j];
li.appendChild(ahref);
output.appendChild(li);
}
}
createListOfFiles(["Google"],["www.google.com"]);
<ul id="listing" style="font-size:120%;"></ul>
您的问题是textContent
属性,您需要将innerText或innerHTML设置为该a
元素。
您没有在a
标签内添加任何文本,因此其大小为0,0并且不可见
const names = [1,2,3];
const hrefs = [1,3];
let output = document.getElementById("listing"); //list elemenst
for (let j = 0; names.length > j; j++) {
var li = document.createElement('li');
li.style.display = "inline";
var ahref = document.createElement('a');
ahref.setAttribute('href',hrefs[j]);
ahref.setAttribute('textContent',names[j]);
// ADD TEXT CONTENT
ahref.innerText = names[j];
li.appendChild(ahref);
output.appendChild(li);
}
<ul id="listing" style="list-style-type:none;background-color:orange;font-size:120%;">
</ul>
,
创建一个文本节点并附加到 anchor 标签
function createListOfFiles(names,hrefs) {
let output = document.getElementById("listing"); //list elemenst
for (let j = 0; names.length > j; j++) {
var li = document.createElement('li');
li.style.display = "inline";
var ahref = document.createElement('a');
ahref.setAttribute('href',hrefs[j]);
//ahref.setAttribute('textContent',names[j]);
var linkText = document.createTextNode(names[j]);// Create a new text node
ahref.appendChild(linkText);
li.appendChild(ahref);
output.appendChild(li);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。