[英]How can i make my new bullet points display a string?
第一次发帖,对不起,如果我做错了什么。
当我尝试用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>
问题是你试图给innerHTML一个对象而不是一个字符串。 innerHTML接受一个字符串 - https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Syntax
如果你想将一个html元素附加到ulist,你需要使用与bodyEl相同的.appendChild()方法 -
function bulletpoint(){
ulist.appendChild(bulletpointEl);
}
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.