2016-06-21 107 views
1

我試圖格式化一些不斷更新的表格的一些數據ajax使用TableSorter排序和格式化

我想浮子數據 成爲這個

1.100.500,00(貨幣)

後,我對它進行排序。

問題是tablesorter只有正確地排列float值,如果它們是第一種格式。我需要做的是:

  1. ajax加載數據時,將其顯示爲貨幣。
  2. 單擊table <th>對數據進行排序時,請刪除(貨幣)貨幣格式並正確排序數據。
  3. 正確排序後,將數據(貨幣)重新格式化爲貨幣。

我已經嘗試過這個:(我發現,它的解決這裏的許多問題在SO)

$.tablesorter.addParser({ 
     // set a unique id 
     id: 'thousands', 
     is: function(s) { 
      // return false so this parser is not auto detected 
      return false; 
     }, 
     format: function(s) { 
      // format your data for normalization 
      return s.replace('.','').replace(/,/g,''); 
     }, 
     // set type, either numeric or text 
     type: 'numeric' 
     }); 


     $("#table_1").tablesorter({ 
      headers: { 
       2: {//zero-based column index 
        sorter:'thousands' 
       } 
      } 
    }); 

,但它不工作。

任何想法?謝謝。

回答

1

有一些固定(demo)四兩件事:

  1. 功能替換週期將只​​刪除一個。所以把它改爲.replace(/\./g, "")(這段時間也需要逃脫)。
  2. 從字符串中刪除$
  3. 用小數點替換,,以便正確解析該值。
  4. 使用內置$.tablesorter.formatFloat函數將值從字符串轉換爲數字。

    $.tablesorter.addParser({ 
        id: 'thousands', 
        is: function(s) { 
        return false; 
        }, 
        format: function(s) { 
        var number = s.replace(/\$/g, '').replace(/\./g, '').replace(/,/g, '.'); 
        return $.tablesorter.formatFloat(number); 
        }, 
        type: 'numeric' 
    }); 
    $(function() { 
        $("table").tablesorter({ 
        theme: 'blue', 
        headers: { 
         0: { 
         sorter: 'thousands' 
         } 
        } 
        }); 
    }); 
    

我共享演示使用我的fork of tablesorter,但代碼也將作爲有望在原來的版本。

+0

我會嘗試並告訴結果 – Lioo

+0

嗨,我更新了代碼,但它沒有工作:(有一件事我沒有在你的小提琴中理解它的價值在你的HTML已經在格式我想(999.999,99),而不是我目前收到的格式(999999.99)。**編輯** woops我的壞。你傳遞的代碼是一個解析器,準備接收該貨幣格式的值,右? – Lioo

+0

以正確的方式再次測試,您的答案奏效,非常感謝! – Lioo