【问题标题】:For each cell in HTML Table column do X?对于 HTML 表格列中的每个单元格,X?
【发布时间】:2018-09-09 23:59:46
【问题描述】:

只是想看看是否有更好的方法来做到这一点。

假设我有您的标准 HTML 表格,其中包含几行和几列数据。我想做的是将函数应用于属于该列的每一行或单元格。我现在正在尝试的是 3 深度循环,实际上并不是最好的。

<table id="myTable"> 
<thead> 
<tr> 
    <th>Last Name</th> 
    <th>First Name</th> 
    <th>Email</th> 
    <th>Due</th> 
    <th>Web Site</th> 
</tr> 
</thead> 
<tbody> 
<tr> 
    <td>Smith</td> 
    <td>John</td> 
    <td>jsmith@example.com</td> 
    <td>$50.00</td> 
    <td>http://www.jsmith.example.com</td> 
</tr> 
<tr> 
    <td>Bach</td> 
    <td>Frank</td> 
    <td>fbach@example.com</td> 
    <td>$50.00</td> 
    <td>http://www.frank.example.com</td> 
</tr> 
<tr> 
    <td>Doe</td> 
    <td>Jason</td> 
    <td>jdoe@example.com</td> 
    <td>$100.00</td> 
    <td>http://www.jdoe.example.com</td> 
</tr> 
<tr> 
    <td>Conway</td> 
    <td>Tim</td> 
    <td>tconway@example.net</td> 
    <td>$50.00</td> 
    <td>http://www.timconway.example.com</td> 
</tr> 
</tbody> 
</table> 

假设我想将网站列字符串大写或用它做一些简洁的事情。 我可能会:

*select the tbody using dom selector or jquery.
*for loop with each column
   *check if the data is what I want
*for loop for each row
   *do my function to each cell

这可能有点慢,我总是尽量避免嵌套循环。 有没有可能使用 Dom 将列视为容器?

IE  for (cell x in Column y)
{ doMyfunction(); }

【问题讨论】:

    标签: javascript jquery css html-table


    【解决方案1】:

    如果你使用 jQuery,你可以使用 .each() 函数:

    $('#myTable td').each(function () {
        // action to perform.  Use $(this) for changing each cell
    });
    

    如果您知道您只想更改一行中的一个特定单元格,那么一旦您知道它是哪个单元格,使用 :eq() 或 :nth-child() 选择器将允许在没有该行的其他人这样做。

    下面的代码将操作行中的第一个单元格,因为 eq() 的索引从 0 开始。

    $('#myTable tr td:eq(0)').each(function () {
        // action to perform.  Use $(this) for changing each cell
    });
    

    下面的代码仍然会操作第一个孩子,但 nth-child() 的索引从 1 开始

    $('#myTable tr td:nth-child(1)').each(function () {
        // action to perform.  Use $(this) for changing each cell
    });
    

    【讨论】:

    • 非常好的功能。甚至没有意识到这一点。
    【解决方案2】:

    如果你只是想设置样式,使用 css 会更快

    tbody tr td:nth-child(4){font-weight:bold;}
    

    据我所知,您也可以在 JQuery 中使用该 css 选择器

    【讨论】:

      【解决方案3】:

      使用 jQuery

      $("td", "#myTable tbody").each(function(index, elem){
      // do my stuff here
      });
      

      【讨论】:

      • 取决于。如果他想绑定相同的功能,那就不行。如果他想根据索引做不同的事情,那么可以。
      猜你喜欢
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多