第一次发帖,如有不妥请见谅
当我尝试用 js 创建一个新列表时,列表元素只在 DOM 中显示 [object HTMLLIElement]。我希望它制作一个新的要点,每次我按下按钮时都会说“你好”。 它只显示这个 https://gyazo.com/f441c11ce81d80ff14ba4e207c1a7e2d
这是我的代码。
var bodyEl = document.querySelector("body");
var ulist = document.createElement("ul");
var bulletpointEl = document.createElement("li");
bulletpointEl.innerHTML = "hello"
bodyEl.appendChild(ulist);
function bulletpoint() {
ulist.innerHTML += bulletpointEl;
}
<button onclick="bulletpoint()">New bulletpoint</button>
最佳答案
您必须使用 appendChild 而不是 innerHTML。要在每次单击按钮时创建新的 li 元素,您必须在函数内创建它。
当内容是简单文本时,我还建议您使用 textContent 而不是 innerHTML。
var bodyEl = document.querySelector("body");
var ulist = document.createElement("ul");
function bulletpoint(){
var bulletpointEl = document.createElement("li");
bulletpointEl.textContent = "hello"
ulist.appendChild(bulletpointEl);
bodyEl.appendChild(ulist);
}
<button onclick="bulletpoint()">New bulletpoint</button>
<a href="../index.html">back</a>
关于javascript - 我怎样才能让我的新项目符号点显示一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53432310/