我是JavaScript的新手,正在学习各种东西。现在我卡在了从列表中添加和删除li元素上。使用jQuery的练习我做得很好,但是现在我在用纯JS版本时遇到了困难。
主要思路是通过点击按钮添加一个新的li元素,并通过点击旁边的X按钮删除该元素。我尝试使用“this”和其他在Stackoverflow类似问题中提到的建议,但对我来说都没有起作用。您能否指导我做错了什么?
P.S.添加功能似乎在片段中可以工作,但控制台记录错误:无法读取null的“addeventlistener”属性。
主要思路是通过点击按钮添加一个新的li元素,并通过点击旁边的X按钮删除该元素。我尝试使用“this”和其他在Stackoverflow类似问题中提到的建议,但对我来说都没有起作用。您能否指导我做错了什么?
P.S.添加功能似乎在片段中可以工作,但控制台记录错误:无法读取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>