4 回答

TA貢獻1809條經(jīng)驗 獲得超8個贊
您需要使用createElement函數(shù)來創(chuàng)建您li
的待辦事項items
。然后在上面使用 appendChild - 也可以考慮使用addEventListener
我還添加了clearAll
按鈕的功能。items
這將使您從列表中清除所有要做的事情。
此外,由于您form
在 HTML 中使用 a ,這意味著默認行為是它將重新加載頁面。要阻止這種情況發(fā)生,請使用preventDefault方法。
現(xiàn)場演示:
var list = document.getElementById("myList")
//Add to do's
document.getElementById("addtodo").addEventListener('click', function(e) {
e.preventDefault()
var inputValue = document.getElementById("newtodo");
var li = document.createElement('li')
li.textContent = inputValue.value
list.appendChild(li)
inputValue.value = ''
}, false);
//Clear all
document.getElementById("clearAll").addEventListener('click', function(e) {
e.preventDefault()
list.innerHTML = ''
}, false);
<body>
<main>
<div>
<form>
<input type="text" name="newtodo" id="newtodo" placeholder="New Todo...">
<button type="submit" id="addtodo">+</button>
</form>
<div class="AddedTodo">
<ul id="myList">
</ul>
</div>
<div>
<button id="clearAll">Clear All</button>
</div>
</div>
</main>
</body>

TA貢獻1790條經(jīng)驗 獲得超9個贊
拳頭按鈕類型不應該是submit它應該是type="button"并且易于使用innerHTML。
<body>
<main>
<div>
<form>
<input type="text" name="newtodo" id="newtodo" placeholder="New Todo...">
<button type="button" id="addtodo">+</button>
</form>
<div class="AddedTodo">
<ul id="myList">
</ul>
</div>
<div>
<p id="clearAll">Clear All</p>
</div>
</div>
</main>
</body>
<script type="text/javascript" src="script.js"></script>
document.getElementById("addtodo").onclick = function addItem() {
const newtodo = document.getElementById("newtodo").value;
const myList = document.getElementById("myList");
myList.innerHTML += '<li>' + newtodo + '</li>';
}

TA貢獻1835條經(jīng)驗 獲得超7個贊
SO 上有很多待辦事項列表示例代碼...
像這樣一個:How do I append more than one child element to a parent element Javascript
你錯過了任何形式提交=>發(fā)送數(shù)據(jù)并加載新頁面(這里它重新定位同一頁面)
你的按鈕是提交,所以你必須跟蹤提交事件,而不是按鈕的點擊事件......
const myForm = document.getElementById('my-form')
, myList = document.getElementById('my-list')
;
myForm.onsubmit=e=>
{
e.preventDefault() // stop the form submit ( don't let him sending data to server, don't let a page quit and loading the same one)
let todoText = myForm.newtodo.value.trim() // get the todo value without spaces before / after
if (todoText!=='')
{
let liTodo = document.createElement('li')
liTodo.textContent = todoText
myList.appendChild(liTodo)
myForm.newtodo.value = '' // cleaner
}
}
<form id="my-form">
<input type="text" name="newtodo" placeholder="New Todo...">
<button type="submit" >+</button>
</form>
<br>
<ul id="my-list"></ul>
添加回答
舉報