简体   繁体   English

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

[英]Find all elements with matching indexes and get largest attribute

I'm trying to dynamically set heights across all table headings based on the tallest corresponding div on its index. 我正在尝试根据其索引上对应的最高div动态设置所有表标题的高度。 I will be using MaterializeCSS which responsively makes the headings display block and the content scroll right to left. 我将使用MaterializeCSS,该方法将响应性地使标题显示块和内容从右向左滚动。

I'll use a super simple example. 我将使用一个非常简单的示例。

<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>

In the example I showed, I'd like to set the height of the th for heading 1 to 100px and the height of th for heading 2 to 200px. 在我展示的示例中,我想将标题1的th的高度设置为100px,将标题2的th的高度设置为200px。

I tried a few things and got completely lost. 我尝试了几件事,完全迷路了。 Maybe I was trying to get too cute with it. 也许我试图变得太可爱了。 The logic I was attempting was: 我尝试的逻辑是:

  • For each th in thead 对于thead每个th
    • Find td with same index as the th within each tr within tbody and get largest height tbody每个tr找到与th索引相同的td并获得最大高度
    • Set height of th 的设置高度th

I get that it would start with $('th').each(function () { //magic goes here }); 我知道它将以$('th').each(function () { //magic goes here });开头$('th').each(function () { //magic goes here });

Here is a Codepen I have to show my progress on it: https://codepen.io/hdwebpros/pen/vjbwyw 这是一个Codepen,我必须显示其进度: https ://codepen.io/hdwebpros/pen/vjbwyw

Thanks in advance for any help or guidance. 在此先感谢您的帮助或指导。 I appreciate it! 我很感激!

You could do the following: 您可以执行以下操作:

  • for each row tr 每行tr
    • for each column td 对于每列td
      • compute the max height h[c] of every column with the same index 计算具有相同索引的每列的最大高度h[c]
  • assign the max height to each column with the same index 将最大高度分配给具有相同索引的每列

 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]); } 
 td { border: 1px solid black; } 
 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM