2011-05-05 62 views
1

在我的應用程序中,用戶單擊刪除按鈕從列表中刪除項目。當最後一個項目被刪除時,它應該顯示一條消息,說沒有更多項目。我的代碼很好地刪除了項目,但在最後一項之後,它不顯示消息。這是爲什麼?如何在jQuery中沒有更多項目時顯示消息

的Jquery:

var optionLinkBox = $('.option-lnk'); 

optionLinkBox.delegate('.um-delete-lnk', 'click', function(e){ 
    var thisElem = $(this); 

    thisElem.closest('li').fadeTo(400, 0, function(){ 
     $(this).slideUp(400, function(){ 
      $(this).remove(); 
     }); 

     if($('.um-card-detail li').length < 1){ 
      // Message to show after the last item 
      $('section:first').text('You don\'t have any payment card saved.'); 
     } 
    }); 

    e.preventDefault(); 
}); 

HTML:

<section> 
    <ul class="um-card-detail">   
    <li class="um-card-li"> 
     <h3>Your card <small>(This is your default card)</small></h3> 
     <div class="option-lnk"> 
     <a href="#">Edit</a> | <a href="#" class="um-delete-lnk">Delete</a> 
     </div> 

     <h3>Some payment details</h3> 
    </li> 

    <li class="um-card-li"> 
     <h3>Your card</h3> 
     <div class="option-lnk"> 
     <a href="#">Edit</a> | <a href="#" class="um-delete-lnk">Delete</a> 
     </div> 

     <h3>Some payment details</h3> 
    </li> 
    </ul> 
</section> 

回答

2

我認爲檢查是最後一個li元素被刪除,甚至之前執行(因爲該元素在回調淡入的去除) 。

將檢查最後一個li的代碼移到fadeIn方法的回調中,它將起作用。

試試這個:

var optionLinkBox = $('.option-lnk'); 

optionLinkBox.delegate('.um-delete-lnk', 'click', function(e){ 
var thisElem = $(this); 

thisElem.closest('li').fadeTo(400, 0, function(){ 
    $(this).slideUp(400, function(){ 
     $(this).remove(); 
     if($('.um-card-detail li').length < 1){ 
      // Message to show after the last item 
      $('section:first').text('You don\'t have any payment card saved.'); 
     } 
    }); 
}); 

e.preventDefault(); 
}); 
+0

@Cyber​​mate:非常感謝您的支持。有用。我會在10分鐘後給出答案。再次感謝。 – Shaoz 2011-05-05 16:52:01

1

這是因爲以下幾點:

if($('.um-card-detail li').length < 1){ 
     // Message to show after the last item 
     $('section:first').text('You don\'t have any payment card saved.'); 
    } 

執行的最後一個項目被刪除之前:

$(this).slideUp(400, function(){ 
    $(this).remove(); 
}); 

供給效果基本show的回調函數方法將在幻燈片操作完成後以及當前函數返回後執行這是400毫秒後,你應該把if語句放在回調中。

$(this).slideUp(400, function(){ 
     $(this).remove(); 
     if($('.um-card-detail li').length < 1){ 
      // Message to show after the last item 
      $('section:first').text('You don\'t have any payment card saved.'); 
     } 
    }); 
0

原因是你有$(this).remove();包裝在一個slideUp()函數中,這需要400毫秒的時間來執行。您的IF語句不會等待slideUp完成執行。要做到這一點,請將語句放在slideUp回調中,如下所示:

$(this).slideUp(400, function(){ 
    $(this).remove(); 
}, function() { 
    if($('.um-card-detail li').length < 1){ 
     // Message to show after the last item 
     $('section:first').text('You don\'t have any payment card saved.'); 
    } 
}); 
相關問題