简体   繁体   English

添加/删除 <li> ul javascript中的元素

[英]Add/remove <li> element from the ul javascript

I am new in JavaScript and still learning various things. 我是JavaScript新手,仍然在学习各种东西。 Right now i'm stuck with adding and removing li elements from the list. 现在,我一直坚持从列表中添加和删除li元素。 I did the exercise just fine using jQuery, but now have difficulties with the pure JS version of the same task. 我使用jQuery做得很好,但是现在使用同一任务的纯JS版本存在困难。

The main idea is to add a new li element by clicking on the button, and remove the the element by clicking on the X button right next to it. 主要思想是通过单击按钮来添加新的li元素,并通过单击其旁边的X按钮来删除该元素。 I have tried using 'this' and other advices mentioned in similar questions here on Stackoverflow, but nothing worked for me. 我已经尝试过使用“ this”和在Stackoverflow上类似问题中提到的其他建议,但对我没有任何帮助。 Could you, please, guide me what am I doing wrong? 能否请您指导我我做错了什么?

PS the adding function seems to be working in snippet, but console logs error: cannot read property 'addeventlistener' of null. PS添加功能似乎在代码段中起作用,但是控制台记录错误:无法读取null的属性'addeventlistener'。

 //declaring the variables var btn = document.getElementsByClassName('btn'); var list = document.getElementById('list'); var add = document.getElementById('add'); //adding a new element to the list add.addEventListener('click', function(){ var newElement = document.createElement('LI'); list.appendChild(newElement); newElement.innerHTML= "I am a new element<button class='btn'>X</button>"; }); //removing the clicked element btn.addEventListener('click', function(){ list.parentNode.removeChild(this); }); 
 ul li { decoration: none; display: block; margin-top: 1em; text-align: center; font-family: 'Avant Garde', Avantgarde, 'Century Gothic', CenturyGothic, AppleGothic, sans-serif; font-size: 18px; } #add { background-color: black; color: white; border: none; width: 280px; font-color: white; border-radius: 8px; font-size: 16px; padding: 15px; outline: none; text-align: center; margin: 20px auto; display: block; } #add:hover { background-color: #28364d; color: white; border: none; outline: none; } #add:active { position: relative; bottom: 2px; } .btn{ margin-left: 10px; border-radius: 10px; background-color: #000; color: white; border: none; outline: none; font-size: 14px; font-family: sans-serif; } .btn:active { position: relative; bottom: 2px; } 
 <div> <ul id="list"> <li class="element">I am a new element<button class="btn">X</button></li> <li class="element">I am a new element<button class="btn">X</button></li> <li class="element">I am a new element<button class="btn">X</button></li> <li class="element">I am a new element<button class="btn">X</button></li> <li class="element">I am a new element<button class="btn">X</button></li> </ul> <button id="add">Add an element to the list</button> </div> 

In your case, btn is a node list of elements, not an element, so you can't attach an event to an array. 在您的情况下, btn是元素的节点列表,而不是元素,因此您无法将事件附加到数组。 You need to iterate through them: 您需要遍历它们:

for(i=0; i < btn.length; i++) {
   btn[i].addEventListener('click', function(){
      list.parentNode.removeChild(this);
   });
}

This returns a non-live collection: 这将返回一个非实时集合:

var btn = document.getElementsByClassName('btn');

Which means that it will only contain the objects which exist at the point of the method call. 这意味着它将仅包含方法调用时存在的对象。 You need to call getElementsByClassName() after the creation of the new li elements, and attach the EventListeners on the invidual buttons. 创建新的li元素后,需要调用getElementsByClassName() ,并将EventListeners附加到单个按钮上。 Just remember not to put an EventListener twice on the buttons. 只要记住不要在按钮上两次放置一个EventListener即可。

A nicer solution 更好的解决方案

Better yet: do not use getElementsByClassName() , just attach the event handler directly in the function, in which you create the new button. 更好的是:不要使用getElementsByClassName() ,只需将事件处理程序直接附加到函数中即可在其中创建新按钮。 That way, you don't have to worry about pre-existing event handlers: 这样,您不必担心预先存在的事件处理程序:

add.addEventListener('click', function(){
    var newElement = document.createElement('LI');
    list.appendChild(newElement);
    newElement.innerHTML= "I am a new element<button class='btn'>X</button>";
    newElement.addEventListener('click', function () {
        this.parentNode.removeChild(this);
    });
});

I am learning too and this was a good little challenge as a newcomer. 我也在学习,作为一个新手,这是一个很好的小挑战。 Thanks to rlemon for pointing us in the right direction with that article link. 感谢rlemon通过该文章链接为我们指出正确的方向。 I learnt something here. 我在这里学到了一些东西。

In case you were interested what I arrived at: https://jsfiddle.net/nyxhj0tg/1/ 如果您对我到达的地方感兴趣,请访问: https : //jsfiddle.net/nyxhj0tg/1/

JS: JS:

var list = document.getElementById('list');
var add = document.getElementById('add');

//adding a new element to the list
add.addEventListener('click', function(){
  var newElement = document.createElement('LI');
  list.appendChild(newElement);
  newElement.innerHTML= "I am a new element<button class='btn'>X</button>";

});

list.addEventListener('click', function(e){
  if(e.target && e.target.nodeName == "BUTTON") {
        console.log("Button ", e, " was clicked!");
    e.target.parentNode.remove();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM