javascript 如何计算 HTML 表格中的行数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11638206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:52:52  来源:igfitidea点击:

How to count the number of rows in a HTML table?

javascriptjqueryhtmlprimefacesdatatable

提问by Myy

I can't seem to find this anywhere. I have a dataTable like this one, and I want to be able to count the number of rows in the dataTable in javascript. how would that be accomplished? thanks!

我似乎无法在任何地方找到这个。我有一个像这样的数据表,我希望能够在 javascript 中计算数据表中的行数。这将如何实现?谢谢!

I need it in javascript because I want to iterate through the datatable and check to see if any rows cantain certain data in them.

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

EXAMPLE PSEUDOCODE

示例伪代码

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

回答by GG.

It would be easier to count the rows with jQuery:

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

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

Demo: http://jsfiddle.net/YLVuK/1/

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

回答by bluedevil2k

Using jQuery, you could simply do

使用 jQuery,你可以简单地做

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

And name your table with an ID of "myTable"

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

回答by Tom

if your table has an id, you can do it as follows:

如果你的表有一个 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
    }
}

回答by Catfish

You can count the number of rows in a datatable on the server side in your backing bean and then set a java object attribute equal to the number of rows. Then in your view, you can set the javascript variable using el expression language. Something like this:

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

Backing 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();
    }
}

In your xhtml file:

在您的 xhtml 文件中:

var tableSize = #{backer.numCars}