根据列和计数中的值对表中的项目进行分组

时间:2014-03-14 11:06:29

标签: jquery

我有下表:

echo '<table>
        <thead">
        <tr>
            <th>Host</th>
            <th>Dest Server</th>
        </tr>
    </thead>

<tbody>';

foreach($xml->children() as $textxml)
{
  echo '<tr>';
  echo '<td>' . $testxml->attributes()->host . "</td>";
  echo '<td>' . $testxml->attributes()->destserver . "</td>";
  echo '</tr>';
}

输出:

Host          Dest Server
server1       ss01
server2       ss01
server3       ss02

JQuery的:

<script type="text/javascript" charset="utf-8">
    var index = $("table thead th:contains('Dest Server')").index() + 1;  //index is zero based, nth-child is 1 based.
    var cells = $("table tbody td:nth-child(" + index + ")");

    var ss01Count = cells.filter(":contains('ss01')").length;
    var ss02Count = cells.filter(":contains('ss02')").length;

    console.log(ss01Count, ss02Count);
</script>

问题:我想在Dest Server列中显示ss01和ss02的出现次数,但控制台日志只显示0,0而不是2,1

非常感谢您的帮助。感谢

1 个答案:

答案 0 :(得分:0)

我认为问题与脚本的执行有关。它是放在表之后还是在表格在页面中呈现之前执行。你可以see here将你的脚本放在$(function(){...})中时工作得很好;

$(function(){

    var index = $("table thead th:contains('Dest Server')").index() + 1; 

    var cells = $("table tbody td:nth-child(" + index + ")");

    var ss01Count = cells.filter(":contains('ss01')").length;

    var ss02Count = cells.filter(":contains('ss02')").length;

    console.log(ss01Count, ss02Count);
})