2017-06-02 62 views
0

我需要動態構建表,但是對它進行排序也是一項要求。動態構建表上的jQuery表分類器

我有很多其他桌子上的tablesorter,但這些是靜態的。我無法使用Ajax接收的數據使其在動態構建的表上工作。 AFAIK在修改數據之後,您需要使用$('myTable').trigger('updateAll');,這是我正在使用的tablesorter分支的confirmed by the maintainer

我在JSFiddle上構建了一個小型演示。

任何想法,我如何得到這個排序動態表或它是一個錯誤?我正在使用最新版本的tablesorter插件和jQuery 1.10.1

EDITS:
1)我也打過電話$('myTable').trigger('destroy');,然後重新初始化它代替使用上述updateAll的。
2)我也嘗試等待,直到我建立了表來初始化tablesorter插件。

+0

請解釋downvote。我的問題是關於主題,有一個完全可行的問題,有一個我最小的相關代碼問題的例子,我已經試過的節目,表明我研究了這一點,並表明我正在繼續嘗試通過我所做的編輯來解決這個問題。它有什麼問題? – PairedPrototype

+2

我無法解決錯誤。但我想我已經發現了這個問題。在控制檯中,tblHead顯示' .... ...「等等。看起來,所有th標籤都在tr標籤之外,這肯定是導致問題的原因之一 –

+0

@ T.Shah認爲''是自動添加了結尾標記,因此導致我的所有''單元被放置在它後面。如果您想提交它作爲答案,我會將其標記爲已解決:) – PairedPrototype

回答

2

As @ T.Shah表示,在thead中,th的值被添加到tr之外。發生這種情況是因爲th的被附加到thead而不是tr在此代碼:

tblHead.append('<th>...</th>'); 

變化在這些線路上構建表的代碼,使其工作(demo):

// Begin the row 
var html = '<tr>'; 

// Fill the table header (thead) row 
for (var i = 0; headerColumns.length - 1 >= i; i++) { 
    var id = headerColumns[i]['id']; 
    var value = headerColumns[i]['value']; 

    // Check to see if this column has an average avalible for it 
    if (averages[id]) { 
    value = 'Average: ' + averages[id] + '<br />' + value; 
    } 

    // Write the table head data 
    html += '<th id="' + id + '"' + '>' + value + '</th>'; 
} 

// End the row 
tblHead.append(html + '</tr>'); 

<tbody>,用於添加一行HTML是不正確,應該用</tr>

tblBody.append('<tr id="tblRow' + key + '"></td>'); 
結束

相反,使用字符串來構建該行:

html = ""; 
// Fill the table body (tbody) with all required rows of data 
for (var key in reportData) { 
    // Some object properties are inherited, we don't want these 
    if (!reportData.hasOwnProperty(key)) { 
    continue; 
    } 

    // Create a new table body row 
    html += '<tr id="tblRow' + key + '">'; 

    // Apply data to each column in the row 
    for (var i = 0; reportData[key].length - 1 >= i; i++) { 
    var id = reportData[key][i]['id']; 
    var value = reportData[key][i]['value']; 

    // Write the column data 
    html += '<td id="' + id + '"' + '>' + value + '</td>'; 
    } 
    html += '</tr>'; 
} 
tblBody.append(html); 

然後觸發 「updateAll」。

字符串用於構建HTML的原因是因爲最好儘可能少地與DOM進行交互以獲得最佳性能。建立一個HTML字符串並添加一次,或者在這個例子中添加兩次 - 一次用於thead,一次用於tbody,而不是附加每個元素。

+0

啊是的,我得到它與類似的修復工作https://jsfiddle.net/kg4v10oq/6/ 看起來'tr'的結束標籤會自動追加,導致'th'被放置在它之後。我不知道我是怎麼看不見的,我也檢查了這個問題。 – PairedPrototype