我需要一些帮助来处理我正在进行的任务。使用JavaScript,我需要在我的removeItem()函数中使用.target事件属性来删除li元素。有人可以帮忙吗?我的代码如下。
function Post(item) {
this.item = item;
this.print = function() {
var s = this.item;
return s;
}
}
var postList = [];
window.onload = init;
function init() {
var submitButton = document.getElementById("submitButton");
submitButton.onclick = getAddedItem;
}
function getAddedItem() {
var itemInput = document.getElementById("item");
var item = itemInput.value;
if (item == null || item == "") {
alert("Please enter an item");
return;
} else {
var post = new Post(item);
postList.push(post);
addPostToList(post);
var theForm = document.querySelector("form");
theForm.reset();
}
function addPostToList(post) {
var postList = document.querySelector("ul");
var li = document.createElement("li");
li.onclick = removeItem(li);
postList.appendChild(li);
li.innerHTML = post.print();
}
};
function removeItem(li) {
var test = document.getElementsByTagName("li");
for (i = 0; i < test.length; i++) {
test[i].onclick = function() {
var test = document.querySelector("li");
if (test) {
var testParent = test.parentElement;
testParent.removeChild(test);
}
}
}
}
&#13;
p {
font-style:italic
}
li:hover {
cursor:pointer
}
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
<title>
</title>
<meta charset="utf-8">
</head>
<body>
<form>
<label for="item">Add an item:</label> <input id="item" size="20" type="text"><br>
<input id="submitButton" type="button" value="Add!">
</form>
<ul>
</ul>
<p>Click an item to remove it from the list.</p>
</body>
</html>
&#13;
答案 0 :(得分:1)
以下是要更改的代码部分(请参阅注释):
function addPostToList(post) {
var postList = document.querySelector("ul");
var li = document.createElement("li");
//Don't apply removeItem here. Just give the function name
//The event will be passed to removeItem
li.onclick = removeItem;
postList.appendChild(li);
li.innerHTML = post.print();
}
function removeItem(e) {
e.target.parentElement.removeChild(e.target);
}
这是一个完整的JSBin:http://jsbin.com/mivonanoga/1/