And*_*ngs 4 javascript asp.net jquery tablesorter
asp.net数据网格的输出不包括jquery tablesorter工作所需的thead和tbody元素.
例如它看起来像这样:
<table>
<tr>this is my header row</tr>
<tr>content row 1</tr>
<tr>content row 2</tr>
<tr>content row 3</tr>
...
<tr>content row n</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
它需要看起来像这样:
<table>
<thead>
<tr>this is my header row</tr>
</thead>
<tbody>
<tr>content row 1</tr>
<tr>content row 2</tr>
<tr>content row 3</tr>
...
<tr>content row n</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
我敲了下面的javascript来动态插入它们,但是表格仍然无法排序.我已经确认,如果我手动将thead和tbody标签直接插入到输出html中,该表是可排序的,但是当我尝试使用DOM时,它似乎不起作用.
我错过了什么?
$(document).ready(function()
{
var tbl = document.getElementById('mytableid');
// new header and body elements to be inserted
var tblHead = document.createElement('thead');
var tblBody = document.createElement('tbody');
// get the first row and the remainder
var headerRow = $(tbl).find('tr:first')
var bodyRows = $(tbl).find('tr:not(:first)');
// remove the original rows
headerRow.remove();
bodyRows.remove();
// add the rows to the header and body respectively
$(tblHead).append(headerRow);
$(tblBody).append(bodyRows);
// add the head and body into the table
$(tbl).append(tblHead);
$(tbl).append(tblBody);
// apply the tablesorter
$(tbl).tablesorter();
}
);
Run Code Online (Sandbox Code Playgroud)
编辑:我在发布问题之前实际上解决了问题,但我认为我会继续发布它,因为它可能对其他人有用...请参阅下面的答案.
显然,幻像<tbody>元素出现在输出中.诀窍是确保在添加生成的内容之前将其删除...希望这对某人有用!
$(document).ready(function()
{
var tbl = document.getElementById('mytableid');
// new header and body elements to be inserted
var tblHead = document.createElement('thead');
var tblBody = document.createElement('tbody');
// get the first row and the remainder
var headerRow = $(tbl).find('tr:first')
var bodyRows = $(tbl).find('tr:not(:first)');
// remove the original rows
headerRow.remove();
bodyRows.remove();
// SOLUTION HERE:
// remove any existing thead/tbody elements
$(tbl).find('tbody').remove();
$(tbl).find('thead').remove();
// add the rows to the header and body respectively
$(tblHead).append(headerRow);
$(tblBody).append(bodyRows);
// add the head and body into the table
$(tbl).append(tblHead);
$(tbl).append(tblBody);
// apply the tablesorter
$(tbl).tablesorter();
}
);
Run Code Online (Sandbox Code Playgroud)