[英]my list function doesn't work in javascript
so i wrote this code that would create a list and then append an input to it on click.所以我写了这段代码来创建一个列表,然后在点击时向它附加一个输入。 really simple.真的很简单。 but the problem is it doesn't work and i have no idea why here is the code:但问题是它不起作用,我不知道为什么这里是代码:
function pushing() {
var li = document.createElement("li");
var inputValue = document.getElementById("inp").value;
var pushchild = document.createTextNode(inputValue);
li.appendChild(pushchild);
}
sub.addEventListener("click", pushing);
the id inp
is an input id. id inp
是输入 id。 thank you谢谢你
Your list item is never appended to a list element.您的列表项永远不会附加到列表元素。
// Cache the elements, // add the button listener, // & focus on the input const list = document.querySelector('ul'); const input = document.querySelector('#inp'); const sub = document.querySelector('#sub'); sub.addEventListener('click', pushing); input.focus(); function pushing() { const li = document.createElement('li'); const text = document.createTextNode(input.value); li.appendChild(text); // Adding the list item to the list element list.appendChild(li); }
<input id="inp" /> <button id="sub">Click</button> <ul></ul>
Add this to the last line of your function.将此添加到函数的最后一行。 Append your newly created li element to the ul.将新创建的 li 元素附加到 ul。
document.querySelectorAll(‘ul’).appendChild(newCreatedLi);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.