2016-11-11 46 views
1

我有下面的代碼:DIV不會在DOM元素移除時顯示,函數是否知道DOM元素移除?

<ul class="ul" id="selected_conditions"> 
    <li class="condition" data-field="asset_locations_name" data-condition="in"> 
    <i class="fa fa-minus-circle delete_condition" aria-hidden="true" title="Click to remove this condition from the list"></i> WHERE asset_locations_name IN(
    <span class="condition_item" data-id="1213381233"> 
    <i class="fa fa-minus-circle delete" title="Click to remove this item from the list" aria-hidden="true"></i> 1213381233 
    </span>, 
    <span class="condition_item" data-id="1212371897"> 
    <i class="fa fa-minus-circle delete" title="Click to remove this item from the list" aria-hidden="true"></i> 1212371897 
    </span>) 
    </li> 
</ul> 

<div id="empty_msg" style="display: none"> 
    There is no conditions 
</div> 

當我點擊小圖標.delete_condition我應該刪除li元素,如果它是在#selected_conditions最後一個然後從#empty_msg DIV刪除display: none。這是我正在做它:

$(function() { 
    $('#selected_conditions').on('click', '.delete_condition', function() { 
    var condition = $(this).closest('.condition'); 
    var conditions = $('#selected_conditions li'); 

    $.confirm({ 
     title: 'Confirm!', 
     icon: 'fa fa-warning', 
     closeIcon: true, 
     closeIconClass: 'fa fa-close', 
     content: 'This will remove the whole condition! Are you sure?', 
     buttons: { 
     confirm: function() { 
      condition.remove(); 

      if (conditions.length == 0) { 
      $('#empty_msg').removeAttr('style'); 
      } 
     } 
     } 
    }); 
    }); 
}); 

它消除了li但不顯示了#empty_msg因爲conditions.length仍然=1。我在Chrome控制檯中調試了代碼,這就是結果,我不知道爲什麼。

爲什麼?不知道該元素已被刪除的功能或DOM?我如何解決這個問題?

也許是我做錯了什麼,如果是這樣的話,我無法找到我在搞亂事情。

我正在使用jQuery Confirm作爲對話框。

這裏是一個Fiddle玩。

回答

1

在刪除項目之後,您需要查詢項目,但是您在刪除項目之前執行該項目,結果是在刪除項目之前計算長度。

var conditions = $('#selected_conditions li'); 

您只需更新您的狀態此得到預期的結果。

if ($('#selected_conditions li').length == 0) { 
    $('#empty_msg').removeAttr('style'); 
} 

這是工作更新的小提琴。 https://jsfiddle.net/8184ok2e/11/