如何检测是否从我的div中删除了所有元素?

时间:2017-01-30 14:43:53

标签: jquery

我想点击add添加一些div框。然后,我希望能够通过单击“删除”按钮再次删除这些框。当所有方框从list中移除后,我想要一个警报说明。我的功能有一个错误,我无法弄清楚:

$( document ).ready(function() {
   $( ".add" ).click(function() {
       var el = $('<div class="box">box to remove<button class="remove">remove</button></div>');
       $(".list").append(el);
   });

   $('.remove').on('click', '.remove', function () {
        $(this).closest(".box").remove();

        if ($(this).children().length < 0) {
            alert("all removed");
        }
    }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="add" style="cursor:pointer">add</div>
<div class="list"></div>

3 个答案:

答案 0 :(得分:3)

&#13;
&#13;
$( document ).ready(function() {
  
 $( ".add" ).click(function() {
 var el = $('<div class="box">box to remove<button class="remove">remove</button></div>');
  $(".list").append(el);
   
   });
   $(document).on('click', '.remove',function () {
      $(this).parent().remove();
      if(!$('.remove').length) alert('All removed');
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="add" style="cursor:pointer">add</div>
<div class="list"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

  1. 您应该使用事件委派on(),因为您的div被动态添加到DOM:

    $('body').on('click', '.remove', function () {
        //Your code
    });
    
  2. 以下条件永远不会实现,因为当没有div时,长度将为0,但绝不会低于零:

    if ($(this).children().length < 0) {
    

    应为== 0

    if ($('.remove').length == 0) {
    
  3. 希望这有帮助。

    $(function() {
    
      $( ".add" ).click(function() {
        var el = $('<div class="box">box to remove<button class="remove">remove</button></div>');
        $(".list").append(el);
      });
    
      $('body').on('click', '.remove', function () {
        $(this).closest(".box").remove();
        
        if ( $('.remove').length == 0) {
          alert("all removed");
        }
      });
    
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="add" style="cursor:pointer">add</div>
    <div class="list"></div>

答案 2 :(得分:1)

问题是长度不能&lt; 0.最低值为0.

试试这个?

$('.remove').on('click', function () {
  $('.list').html('');

  if ($(this).children().length === 0) {
    alert("all removed");
  }
});