2 回答

TA贡献2051条经验 获得超10个赞
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var shoppingListItems = ["Notebook", "Jello", "Spinach", "Rice", "Birthday Cake", "Candles"]
function inputLength() {
return input.value.length;
}
function createListElement(text, index) {
var li = document.createElement("li");
var deleteBtn = document.createElement("button");
deleteBtn.itemId = index
deleteBtn.onclick = deleteItem.bind(null, index)
deleteBtn.appendChild(document.createTextNode("Delete"))
li.appendChild(document.createTextNode(text));
li.appendChild(deleteBtn);
ul.appendChild(li);
}
function addListAfterClick() {
if (inputLength() > 0) {
shoppingListItems.push(input.value)
createListElement(input.value, shoppingListItems.length - 1);
}
}
function addListAfterKeypress(event) {
if (inputLength() > 0 && event.keyCode === 13) {
shoppingListItems.push(input.value)
createListElement(input.value, shoppingListItems.length - 1);
}
}
function deleteItem(itemId) {
var itemXpath = "//li[text()='"+shoppingListItems[itemId]+ "']";
var item = document.evaluate(itemXpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
item.remove();
}
function initPage() {
shoppingListItems.forEach(function(element, index) {
createListElement(element, index)
})
}
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
window.onload = initPage;
<!DOCTYPE html>
<html>
<head>
<title>Javascript + DOM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul></ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

TA贡献1803条经验 获得超3个赞
你可以这样做:
HTML:
<ul>
<li class="bold red" random="23">Notebook</li>
<li id=li1>Jello <input id='btn1' type="submit" value='-'></input></li>
<li>Spinach</li>
<li>Rice</li>
<li>Birthday Cake</li>
<li>Candles</li>
</ul>
Javascript:
var btn = document.getElementById('btn1');
btn.onclick = function () {
document.getElementById('li1').remove();
this.remove();
};
你可以玩这个例子:
https://jsfiddle.net/be4psyrL/
添加回答
举报