remove() not working when trying to remove <li> generated from a button

问题: I have a button that adds li to the ordered list. Within this item added, there is a delete button. I'm trying to have this button nested within the li delete itself and pa...

问题:

I have a button that adds li to the ordered list. Within this item added, there is a delete button. I'm trying to have this button nested within the li delete itself and parent but remove() does not seem to work.

$('.add').click(()=>{
  var item = "<li>Item - <button class='delete'>Delete</button></li>"
  
  $('ol').append(item);
  
});

$('ol').on( 'click','.delete' ,(e)=>{
  console.log('clicked');
  
  $(e).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol>

</ol>
<button class='add'>Add</button>


回答1:

Use $(e.target).parent().remove();, since e.target tells what element was clicked.

The reason your add function works, it because you don't have to interact with the element you click on.

Demo

$('.add').click(()=>{
  var item = "<li>Item - <button class='delete'>Delete</button></li>"
  
  $('ol').append(item);
  
});

$('ol').on( 'click','.delete' ,(e)=>{
  
  $(e.target).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol>

</ol>
<button class='add'>Add</button>


回答2:

This will do it:

$('ol').on('click', '.delete', function () {
  console.log('clicked');
  $(this).parent().remove();
});
  • 发表于 2019-02-24 08:16
  • 阅读 ( 158 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除