仅向列表中的第一个按钮添加功能

Add functionality to first button in list only

本文关键字:按钮 添加 功能 第一个 列表      更新时间:2023-09-26

My HTML (精简版)

<ul>
   <li>
      <p></p>
      <p></p>
      <button type="button">Remove</button>
   </li>
   <li>
      <p></p>
      <p></p>
      <button type="button">Remove</button>
   </li>
</ul>

我的JavaScript

$('body').on('click', 'li > button', function() {
  $(this).parent().remove();
  if($('li > button').length === 1) { // if this is the only button
    $(this).parent().parent().remove(); // remove whole list
    // remove some other elements outside the list      
  }
  if($(this).parent().is(':first')) { // if this first li in ul 
    if (confirm("...")) {
      $(this).parent().remove();    
    }
  }
});

基本上,我要做的是:

  • 创建第一个按钮以删除父列表项
  • 如果该按钮是<ul>中唯一的按钮,请删除整个列表和另一个元素

我怎样才能正确地完成这项工作?

更改函数以检查是否删除了最后一个<li>(阅读:<ul>不再<li>):

$('body').on( 'click', 'li > button', function() {
    var list = $(this).closest( 'ul' );
    $(this).parent().remove()
    //* if the UL is empty we can remove it altogether
    if( list ).find( 'li' ).length == 0 ) remove( list ); 
});

你只需要评估是否有多个元素,试试这个:

$('body').on('click', 'li > button', function() {
   if(($('li > button').length > 1)) {
     $(this).parent().remove();
   } else {
     $(this).parents('ul').remove();
     console.log('Remove other items')
   }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
   <li>
      <p></p>
      <p></p>
      <button type="button">Remove</button>
   </li>
   <li>
      <p></p>
      <p></p>
      <button type="button">Remove</button>
   </li>
</ul>