[英]How to remove Child element of ul on double click?
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var list=document.querySelectorAll("li")[0];
function inputLength(){
return input.value.length;
}
function createListElement(){
var li=document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value="";
}
function addListAfterClick(){
if (inputLength()>0){
createListElement();
}
}
function removeList(){
ul.childNode.removeChild();
}
function addListAfterEnter(event){
if(inputLength()>0 && event.keyCode==13){
createListElement();
}
}
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterEnter);
list.addEventListener("dblclick", removeList);
I am trying to create a shopping list, where I want to create a function, when I double click any我正在尝试创建一个购物清单,当我双击任何一个时,我想在其中创建一个 function
I am getting below error prompt in console log:我在控制台日志中收到以下错误提示:
dom-event.js:26 Uncaught TypeError: Cannot read properties of undefined (reading 'removeChild') at HTMLLIElement.removeList dom-event.js:26 Uncaught TypeError: 无法在 HTMLLIElement.removeList 中读取未定义的属性(读取“removeChild”)
Element.childNode
doesn't exist on HTML elements. Element.childNode
不存在于 HTML 个元素上。 However you have Element.childNodes
( https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes ) that returns a collection of all elements nested under the given Element
.但是,您有
Element.childNodes
( https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes ),它返回嵌套在给定Element
下的所有元素的集合。
In your case I suggest you'd use an event listener for each li
and remove it when it's clicked (or doubleclicked).在您的情况下,我建议您为每个
li
使用一个事件侦听器,并在单击(或双击)时将其删除。
Example:例子:
const l = document.getElementById("dynlist"); const items_data = ["some", "list", "items"]; function onListItemClick(event) { l.removeChild(event.target) } items_data.forEach(lidata => { const li = document.createElement("li"); li.textContent = lidata; li.addEventListener("click", onListItemClick); l.appendChild(li); })
<ul id="dynlist"> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.