[英]my list function doesn't work in javascript
所以我寫了這段代碼來創建一個列表,然后在點擊時向它附加一個輸入。 真的很簡單。 但問題是它不起作用,我不知道為什么這里是代碼:
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);
id inp
是輸入 id。 謝謝你
您的列表項永遠不會附加到列表元素。
// 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>
將此添加到函數的最后一行。 將新創建的 li 元素附加到 ul。
document.querySelectorAll(‘ul’).appendChild(newCreatedLi);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.