2016-11-11 7 views
1

私は、次のコードがあります:私はli要素を削除し、それが#selected_conditionsで最後の一つだならば、#empty_msg DIVからdisplay: noneを削除する必要があります小さなアイコン.delete_conditionをクリックするとDOM要素の削除時にDIVが表示されないため、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> 

を。これは私がそれをやっている方法です:

$(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が削除されますがconditions.lengthまだ=1以来#empty_msgまで表示されません。私はChrome Consoleでコードをデバッグしていますが、それが結果です。理由はわかりません。

なぜですか?その要素が削除された関数または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/

関連する問題