查找具有匹配索引的所有元素并获取最大属性

时间:2018-05-21 13:36:39

标签: javascript jquery html

我正在尝试根据索引上最高的相应div动态设置所有表格标题的高度。我将使用MaterialiseCSS,它响应地生成标题显示块,内容从右向左滚动。

我将使用一个非常简单的例子。

<thead>
 <tr>
  <th>Heading 1</th>
  <th>Heading 2</th>
 </tr>
</thead>
<tbody>
  <tr>
    <td>This content is 100px</td> 
    <td>This content is 50px</td>
  </tr>
  <tr>
    <td>This content is 50px</td>
    <td>This content is 200px</td>
  </tr>
</tbody>

在我展示的示例中,我想将标题1的th的高度设置为100px,将标题2的高度th设置为200px。

我尝试了一些事情并完全迷失了。也许我试着用它太可爱了。我尝试的逻辑是:

  • th中的每个thead
    • td内的每个th内找到与tr具有相同索引的tbody并获得最大身高
    • 设置th
    • 的高度

我知道它会以$('th').each(function () { //magic goes here });

开头

以下是Codepen我必须在其上展示我的进展:https://codepen.io/hdwebpros/pen/vjbwyw

提前感谢您的任何帮助或指导。我很感激!

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

  • 每行tr
    • 每列td
      • 计算具有相同索引的每列的最大高度h[c]
  • 为具有相同索引的每列指定最大高度

&#13;
&#13;
var h = [];
$("#table tr").each(function(r, tr) {
  $(tr).find("td").each(function(c, td) {
    if (c == 0) {
      h.push($(td).height());
    } else {
      if ($(td).height() > h[c]) {
        h[c] = $(td).height();
      }
    }
  });
});
for (var c = 0; c < h.length; c++) {
  $("#table td:eq(" + c + ")").css("height", h[c]);
}
&#13;
td {
  border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
  <thead>
    <th>Heading 1</th>
    <th>Heading 2</th>
  </thead>
  <tbody>
    <tr>
      <td style="height: 100px;">This content is 100px</td>
      <td style="height: 50px;">This content is 50px</td>
    </tr>
    <tr>
      <td style="height: 50px;">This content is 50px</td>
      <td style="height: 200px;">This content is 200px</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;