2014-09-28 58 views
0

我有一個函數下面做一個ajax後從數據庫中刪除一行,並且在ajax成功後它將隱藏實際的元素。jQuery返回相同數量的元素已被刪除

這是我遇到的問題:

可以說我有我的網頁上5個元素。成功$ .post()後,它隱藏了一個元素,現在頁面上有4個元素。現在當我點擊刪除鏈接.delete_items時,它仍然返回5個元素作爲控制檯日誌中的.length而不是4。無論我點擊刪除按鈕多少次,它都會返回5。

我翻了幾遍我的代碼,我似乎無法找出爲什麼它返回相同的數字。

任何幫助將非常感激。下面是我的代碼

var menuType = "baseMenu"; //Set global var 

    function countElements(ajax_item_key, ajax_item_val, item_input_class, ajax_cat_key, cat_id){ 


      //This deletes the item only 

      o[ajax_item_key] = ajax_item_val; 


       /* @var count_all_item_inputs 
Count all the input fields that has that has a class name of the passed param 
       item_input_class. Filter the selection with by choosing only the classes with the passed in cat_id 

      Example of an actual HTML item_input : 
      <input class="menu_item_input 2704" type="text" value="Test" name="items_and_prices[21518][]"> */ 

      var count_all_item_inputs = $(item_input_class+'[class*="'+cat_id+'"]').length; 
      console.log(count_all_item_inputs); // This keep returning the same value?? 

      //This deletes item and category if there was one input left to be deleted 
      if(count_all_item_inputs == 1) { 
       o[ajax_cat_key] = ajax_cat_val; 
       var hide_category = true; 
       return hide_category; 
      } 



    } 

    $(.delete_item).on("click", function(){ 

      if(menuType === "baseMenu") { 

       /* 
       @baseMenuId - key to send at the ajax post 
       @id - value defined in my script didn't include it on this example to make things simple 
       @.menu_item_input input class to pass in so that it will count how many inputs are left after a successful jquery post 
       @deleteAllFromBaseMenu - Another jquery key to send if a condition is met inside the countElement function 
       @cat_id - The category id to send alongside with the deleteAllFromBaseMenu 
       */ 

       var hide_category = countElements("baseMenuId", id, ".menu_item_input","deleteAllFromBaseMenu", cat_id); 

    }); 

    $.post("../../include/functions/menuDisplay/MenuCrud/menuDelete.php", o) 

       .fail(function(){ 
        //console.log("deletion failed"); 
       }) 

       .done(function(){ 
        $("div#"+id).hide(); 
        if(hide_category == true){ 
         $("div#"+cat_id).hide(); 
        } 
       }); 

       return false; 
     } else { 
      return false; 
     } 
+0

我沒有看到你刪除任何html元素 – 2014-09-28 00:46:44

回答

0

你計算所有的選擇和匹配即使你隱藏的元素,你不刪除它的元素,爲此他們仍然計數總。您可以通過添加篩選器:visible來修改選擇器以僅顯示可見元素。

例如,具有以下html,如果我們使用選擇器$("div:visible"),我們只會得到第二個div,而如果我們只是使用$("div"),我們將同時定位這兩個。

<div style='display:none'>A</div> 
<div>B</div> 

,對於:visible過濾器的工作如你所期望的元素需要服用一些空間在文件中,換句話說,如果它是空的,儘管不一定是隱藏的,它會不算數。

-1

如果檢查$('*').length然後使用.remove()代替.hide()然後檢查$('*').length和瓶坯簡單的數學,我想你已經知道了,除非有其他的問題,我沒有注意到。