I wrote the code below to dynamically add li elements to a ul element. I want the user to be able to click on any one of them and have that li item removed. I know how to do this with JQuery but I want to know how to do it with vanilla JavaScript.I understand that removeChild() is the only method at my dispose to do this but I am a bit confused as to how to use it to accomplish the task at hand.
Thank you.
HTML
<form id="input-form">
<input id="input-field" type = "text"/>
<button>Submit</button>
</form>
<ul id="list" >
</ul>
JavaScript
var form = document.getElementById("input-form");
function getInput(event){
event.preventDefault();
var inputValue = document.getElementById("input-field").value
form.reset();
document.getElementById("list").innerHTML += "<li>"+ inputValue +"</li>";
}
form.addEventListener("submit",getInput,false)
答案 0 :(得分:1)
试试这个:
http://jsfiddle.net/3wk0866o/1/
我刚刚添加了这个监听器功能:
function removeItem(e) {
var target = e.target;
if(target.tagName !== 'LI') return;
target.parentNode.removeChild(target);
}
list.addEventListener('click', removeItem);
它将一个事件监听器添加到&#34;列表&#34; UL
元素,并侦听其中的点击次数。 e.target
是点击的元素,如果点击的元素不是LI
元素,则函数只是returns
。如果是,则删除该元素及其所有子元素。
如果您想知道删除元素的最后一位是如何工作的:
target.parentNode
找到点击的LI
元素(UL
)的父元素,然后您只需在该节点上调用removeChild
,因为LI
是UL
的子元素。您也可以直接在元素上使用remove方法,但尚未得到很好的支持。
请注意,如果LI
元素包含子级,则可能会遇到问题。在这种情况下,目标可能会显示为LI
个孩子中的一个,而不是LI
。要解决此问题,您可以使用遍历DOM的循环,直到它到达UL
元素,或直到找到要删除的LI
元素:
http://jsfiddle.net/3wk0866o/3/
function removeItem(e) {
var target = e.target;
while(target.tagName !== 'UL') {
if(target.tagName === 'LI') {
return target.parentNode.removeChild(target);
}
target = target.parentNode;
}
}
list.addEventListener('click', removeItem);
如果您的LI
元素只包含其中的文字,那么第一个解决方案就足够了。
答案 1 :(得分:0)
您可以使用parent.removeChild(child)删除该项目,但您可能在查找子项时遇到问题,因为该项目已动态添加。
2建议:
答案 2 :(得分:0)
您可以直接向新子项添加onclick
事件侦听器。
function getInput(event){
event.preventDefault();
var inputValue = document.getElementById("input-field").value
console.log(inputValue)
form.reset(); // _______________Reset method
// Create new element.
var new_li = document.createElement('li');
new_li.innerHTML = inputValue;
// When it is clicked, remove it.
new_li.onclick = function() {
this.remove();
};
// Append element as child to list.
document.getElementById("list").appendChild(new_li);
}