纯JavaScript:单击子元素时删除元素

时间:2018-06-28 20:03:34

标签: javascript html css performance javascript-events

所以我有

<ul id="list">
  <li>Some text <span class="removeParent">X</span></li>
</ul>

当单击span.removeParent时,必须删除li。

这很简单,但是我想到的唯一(不幸的是正在工作)的解决方案是:

span.addEventListener("click", this.parentElement.parentElement.removeChild(this.parentElement);

可能没有上下文,因此这是完整的待办事项应用程序的链接: https://jsfiddle.net/w246hn3b/3/

我不确定

this.parentElement.parentElement.removeChild(this.parentElement);

是最好,最有效的解决方案

1 个答案:

答案 0 :(得分:3)

这是事件委托的绝佳用例。由于click事件会将DOM扩展到父节点,因此您可以在根祖先上监听click事件,然后检查clicked元素是否与您的目标类型匹配。

var todolist = document.getElementById('todolist');
todolist.addEventListener('click', function(e){
  if(e.target.matches('.remove')){
    todolist.removeChild(e.target.parentNode);
  }
});
.remove {
    color: #821818;
    display: inline-block;
    padding: 3px 10px;
    border: 1px solid #d84c4c;
    border-radius: 2px;
    cursor: pointer;
    position: absolute;
    right: 0px;
    top: 0px;
    height: 100%;
    box-sizing: border-box;
    background: #f1bbc0;
    font-weight: 700;
    font-size: 25px;
}
#todolist{
  list-style:none;
}
#todolist li{
  display:block;
  position:relative;
  padding:8px 6px;
  width:300px;
  margin:5px 0px;
  border-radius:2px;
  box-shadow: 0 3px 4px 0 rgba(0, 0, 0, 0.14), 0 1px 8px 0 rgba(0, 0, 0, 0.12), 0 3px 3px -2px rgba(0, 0, 0, 0.4);
}
<ul id='todolist'>
    <li>1<span class='remove'>&times;</span></li>
    <li>2<span class='remove'>&times;</span></li>
    <li>3<span class='remove'>&times;</span></li>
    <li>4<span class='remove'>&times;</span></li>
    <li>5<span class='remove'>&times;</span></li>
    <li>6<span class='remove'>&times;</span></li>
    <li>7<span class='remove'>&times;</span></li>
    <li>8<span class='remove'>&times;</span></li>
    
  </ul>

有关事件委托的一些资源: https://gomakethings.com/why-event-delegation-is-a-better-way-to-listen-for-events-in-vanilla-js/

https://davidwalsh.name/event-delegate