[英]How to delete items and clear a form using javascript
我為發布這個問題道歉,我只是在學習JavaScript並嘗試使用其他帖子中的信息,但卻無法讓我的代碼工作。 對象是創建一個li標簽並將列表項插入到這個新創建的標簽中,然后分配一個事件處理程序,以便在用戶單擊它時刪除該項。 我有列表填充,如果我硬編碼它可以刪除一個項目,但不能在我的生活中弄清楚如何將被點擊的項目的值分配給removeItem函數。 我還試圖在輸入項目時清除列表,但不斷收到錯誤“對象不支持屬性或方法'重置'”。 如果有人能指出正確的方向,我將不勝感激。 謝謝!
<!doctype html>
<html lang="en">
<head>
<title> Add and delete items Objective </title>
<meta charset="utf-8">
<style>
p {
font-style: italic;
}
li:hover {
cursor: pointer;
}
</style>
<script>
// your code here!
var itemList = [];
window.onload = init;
function init() {
var addButton = document.getElementById("submitButton");
addButton.onclick = addItem;
//var itemList = document.getElementById("list");
var itemsList = document.getElementsByTagName("li");
itemsList.onclick = removeItem;
}
function addItem() {
var newItem = document.getElementById("item").value;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(newItem));
ul.appendChild(li);
itemList.push(newItem);
document.getElementById("item").reset();
}
function removeItem() {
var editList = document.getElementsByTagName("li");
// var editList = document.getElementsById("list");
for (var i = 0; i < editList.length; i++) {
var item = editList[i];
if(editList.options[i].selected) {
editList.removeChild(editList.childNodes[i]);
}
}
}
</script>
</head>
<body>
<form>
<label form="item">Add an item: </label>
<input id="item" type="text" size="20"><br>
<input id="submitButton" type="button" value="Add!">
</form>
<ul id="list">
</ul>
<p>
Click an item to remove it from the list.
</p>
</body>
</html>
為什么不將輸入的項的值設置為空字符串而不是使用reset?
document.getElementById("item").value = "";
至於刪除列表項...
for (var i = 0; i < ul.children.length; i++) {
ul.children[i].addEventListener("click", removeItem);
}
你只能重置表格,所以你必須選擇表格,然后重置將起作用。 fe:
document.forms [0] .reset段()
您的代碼是將eventhandler添加到所有現有的li-Elements,如果稍后創建一些新的li-Elements,則必須手動將eventhandler添加到它。 fe在您的addItem-Function中具有:
li.onclick = removeItem;
推動新物品后
在removeItem-Function中,您可以通過此元素訪問被單擊的元素,因此您可以使用以下方法僅刪除該元素:
this.remove()
您可以更改addItem()和removeItem()函數:
function addItem() {
var newItem = document.getElementById("item").value;
$('#list').append("<li id='" + newItem + "' onclick='removeItem(this)'>" + newItem + "</li>");
}
function removeItem(id) {
$(id).remove();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.