javascript Javascript获取整个第二列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22097155/
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-27 22:25:56  来源:igfitidea点击:

Javascript get entire 2nd column

javascriptcells

提问by JohnB

I have searched for a solution to this issue everywhere but nothing has worked. I have successfully pulled the first column but I am unable to pull the 2nd column. The following code pulls the entire 1st column successfully.

我到处都在寻找解决此问题的方法,但没有任何效果。我已成功拉取第一列,但无法拉取第二列。以下代码成功拉取了整个第一列。

I changed .cellsto [1]and it pulls nothing. I have tried :nth-child(1)but that doesn't work either. I feel I am missing something very trivial. Any help is very much appreciated.

我改变.cells[1],它什么也没拉。我试过了,:nth-child(1)但这也不起作用。我觉得我错过了一些非常微不足道的东西。很感谢任何形式的帮助。

function F0416()
{
    var tab = document.getElementById('partTable');
    var l = tab.rows.length;

    var s = '';
    for ( var i = 0; i < l; i++ )
    {
        var tr = tab.rows[i];

        var cll = tr.cells[0];

        s += ' ' + cll.innerText;
    }
    document.write(s);
}

回答by user13500

First and foremost. Never ever use l(lower case el) as a variable. It is far to similar to 1(one). Also be careful with upper case "o", and upper-case "i". Lowercase "o" is also often disliked.

首先也是最重要的。永远不要使用l(小写 el) 作为变量。它与1(一)非常相似。还要注意大写“o”和大写“i”。小写的“o”也经常被人讨厌。

It might look OK now, but when you review it in 6 months or a year, perhaps not so much. Also consider others might have to both read and modify your code.

现在看起来可能还不错,但是当你在 6 个月或一年后回顾它时,也许不会那么多。还要考虑其他人可能必须阅读和修改您的代码。

Enough about that.

够了。



Your code, as it is, should work. If you do not get the desired result then the problem is elsewhere.

您的代码应该可以正常工作。如果你没有得到想要的结果,那么问题就出在别处。

Make it reusable

使其可重复使用

However, to simplify the code and make it easier to re-use, you can add a parameter for idof the table as well as desired column. Resulting function could be something like this, with some extra checks:

但是,为了简化代码并使其更易于重用,您可以为表的id以及所需的列添加参数。结果函数可能是这样的,有一些额外的检查:

function getColumn(table_id, col) {
    var tab = document.getElementById(table_id);
    var n = tab.rows.length;
    var i, s = null, tr, td;

    // First check that col is not less then 0
    if (col < 0) {
        return null;
    }

    for (i = 0; i < n; i++) {
        tr = tab.rows[i];
        if (tr.cells.length > col) { // Check that cell exists before you try
            td = tr.cells[col];      // to access it.
            s += ' ' + td.innerText;
        } // Here you could say else { return null; } if you want it to fail
          // when requested column is out of bounds. It depends.
    }
    return s;
}

var txt = getColumn('partTable', 2);

Check for failure

检查故障

By using nullas initial value for s, we can compare returned result with nullto see if it was successful.

通过将null用作 的初始值s,我们可以将返回的结果与null进行比较,看看它是否成功。

if (txt === null) {
    // Report error, or at least not work on "txt".
}

Simplify

简化

Once you really understand it you can, if you want, simplify the loop to something like this:

一旦你真正理解了它,如果你愿意,你可以将循环简化为这样的:

for (i = 0; i < n; i++) {
    if (tab.rows[i].cells.length > col) {
        s += ' ' + tab.rows[i].cells[col].innerText;
    }
}

Use Array:

使用数组:

If you are going to use the cells one by one the best approach would be to return an Array instead of a string. Then you can loop the array, or if you want it as a string simply join it with desired delimiter. This would most likely be the most useful and reusable function.

如果您要一个一个地使用单元格,最好的方法是返回一个数组而不是一个字符串。然后你可以循环数组,或者如果你想要它作为一个字符串,只需将它与所需的分隔符连接起来。这很可能是最有用和可重用的功能。

// In function:
arr = [];

// In loop:
arr.push(tab.rows[i].cells[col].innerText);

var cells = getColumn("the_id", 2);
var text = cells.join(' ');


Demo:

演示:

Fiddle demo with array

Fiddle demo with array



Speed.

速度。

If your table cells does not contain any <script>or <style>, which they should not, you can also consider using textContentover innerText. Especially if table is large. It is a much faster. Here is a short article on the subject from Kelly Norton:

如果您的表格单元格不包含任何<script>or <style>,它们不应该包含,您也可以考虑使用textContentover innerText。特别是如果桌子很大。这是一个更快的。这是凯利诺顿关于这个主题的一篇简短文章:

回答by Andres Orav

// This pulls all columns
function getAllCells(table) {
    var result = [];

    for(var i = 0, j = 0, l = table.rows.length, l2 = 0; i < l; i++) {
        for(j = 0, l2 = table.rows[i].cells.length; j < l2; j++) {
            result.push(table.rows[i].cells[j].innerText);
        }
    }

    return result.join(',');
}

回答by Andy

You could try this:

你可以试试这个:

1) Add the existing code to a function so that you can pass in the column parameter.

1) 将现有代码添加到函数中,以便您可以传入列参数。

2) tr.cells[0]should be changed to tr.cells[col]using the passed-in parameter.

2)tr.cells[0]应该改为tr.cells[col]使用传入的参数。

3) change innerTextto innerHTMLas innerText doesn't work on some browsers.

3)改变innerTextinnerHTML如的innerText不适用于某些浏览器。

function getCol(col) {
  var s = '';
  for (var i = 0; i < l; i++) {
    var tr = tab.rows[i];
    var cll = tr.cells[col];
    s += ' ' + cll.innerHTML;
  }
  return s;
}

console.log(getCol(1)) // 222 in my example

Fiddle

小提琴