2011-11-21 98 views
1

減去我用jQuery挺新的,下面的代碼是2個不同的代碼的拼貼畫,我發現來實現我的目標刪除錶行,從總和

我有一個表的圖像,單擊時它刪除一個表格行,這是下面代碼的第一部分。

腳本的第二部分中找出所有表中的行

我試圖讓這個當你刪除行之和也相應改變的總和。因此,當您刪除表格行時,該表格行中的金額將從總表中扣除。我需要和改變根據行刪除

jQuery的一部分刪除表格行的jQuery

$(document).ready(function(){ 
     $('table#FeatureMatrix td a.delete').click(function() 
     { 

      { 
       var id = $(this).parent().parent().attr('id'); 
       var data = 'id=' + id ; 
       var parent = $(this).parent().parent(); 




         parent.fadeOut('slow', function() 
              {$(this).remove();}); 
        return false;  
      } 



     }); 

部分,計算所有錶行

$(document).ready(function() { 
    //this calculates values automatically 
    calculateSum(); 

    $(".txt").live("keydown keyup", function() { 
     calculateSum(); 
    }); 
}); 
     function calculateSum() { 
      var sum = 0; 
      //iterate through each textboxes and add the values 
      $(".txt").each(function() { 
       //add only if the value is number 
       if (!isNaN(this.value) && this.value.length != 0) { 
        sum += parseFloat(this.value); 

       } 
       else if (this.value.length != 0){ 

       } 
      }); 
      $("#sum").html(sum.toFixed(2)); 
     } 

如果總和有人希望看到網頁上的示例頁面,這是鏈接http://webiceberg.net/Prices.php,如果您需要更多關於代碼的詳細信息,還可以查看頁面的源代碼。

回答

1

你只需要調用calculateSum()當您刪除行(整理碼了一點,以及!):

$('table#FeatureMatrix td a.delete').click(function() { 
    var id = $(this).parent().parent().attr('id'); 
    var data = 'id=' + id ; 
    var parent = $(this).parent().parent(); 

    parent.fadeOut('slow', function() { 
     $(this).remove(); 
     calculateSum(); 
    }); 

    return false;     
}); 

注意,它有$(本)之後進行。在回調中刪除(),否則在實際刪除該行之前您將調用計算。

如果您擔心它調用calculateSum直接再火一個自定義事件,並聽取了這一點,然後重新計算:

$('table#FeatureMatrix td a.delete').click(function() { 
    var id = $(this).parent().parent().attr('id'); 
    var data = 'id=' + id ; 
    var parent = $(this).parent().parent(); 

    parent.fadeOut('slow', function() { 
     $(this).remove(); 
     $.event.trigger("rowDeleted"); // fire custom event 
    }); 

    return false;     
}); 

後來聽此事件:

$('#sum').bind('rowDeleted', function() { // listen for custom event 
    calculateSum(); 
}); 
+0

calculateSum函數在此處不可見。此外,它不會太擔心......當需要計算另一個度量或添加一行時會發生什麼? –

+0

看起來像calculateSum對我來說是全球性的。我添加了一個應該分離問題的編輯。 –

+0

好的,所以我把它插入我的代碼,它的作用就像一個魅力,並感謝清理代碼對我來說,你讓我的一天因爲我不得不向今晚的潛在客戶展示這一點,謝謝一堆 – Gunnit

1

嘗試以下操作:

$("table#FeatureMatrix").bind("DOMSubtreeModified", function() { 
    calculateSum(); 
}); 

這將重新計算每個t的總和ime表格被修改(它也可用於添加的行)

+0

好吧,我試過這個以及在關閉文檔準備功能之前添加它,它也像魅力一樣工作,謝謝 – Gunnit