如何计算HTML表中的行数?

时间:2012-07-24 19:44:21

标签: javascript jquery html primefaces datatable

我似乎无法在任何地方找到它。我有一个像this one这样的dataTable,我希望能够在javascript中计算dataTable中的行数。怎么会这样呢?谢谢!

我在javascript中需要它,因为我想遍历数据表并检查是否有任何行包含其中的某些数据。

示例PSEUDOCODE

var tableSize = someway to get table size;
for (i = 0; i < tableSize; i++) {
if (dataTable.row(i).value == "someValue") {
    //do something
}

4 个答案:

答案 0 :(得分:11)

使用jQuery计算行数会更容易:

var tableSize = $('#myTable tbody tr').length;

演示:http://jsfiddle.net/YLVuK/1/

答案 1 :(得分:1)

使用jQuery,你可以简单地做

var tableSize = $("#myTable").find("tbody").find("td").length;

并使用ID“myTable”命名您的表

答案 2 :(得分:0)

如果您的表具有ID,则可以按如下方式执行:

var table = document.getElementById("tableId");
for(var i = 0, ceiling = table.rows.length; i < ceiling; i++) {
    var row = table.rows[i]; // this gets you every row
    for(var j = 0, ceiling2 = row.cells[j]; j < ceiling2; j++) {
        var cell = row.cells[j]; // this gets you every cell of the current row in the loop
        var cellContent = cell.innerHTML; // this gets you the content of the current cell in the loop
    }
}

答案 3 :(得分:0)

您可以计算辅助bean中服务器端数据表中的行数,然后将java对象属性设置为等于行数。然后在您的视图中,您可以使用el表达式语言设置javascript变量。像这样:

支持bean:

public class backer() {
    List<Cars> cars = new ArrayList<Cars>();

    public List<Cars> getCars() {
        return cars;
    }

    public void setCars(List<Cars> cars) {
        this.cars = cars;
    }

    public int numCars() {
        return cars.size();
    }
}

在你的xhtml文件中:

var tableSize = #{backer.numCars}
相关问题