如何用javascript检查给定html表有多少列?

| 那就是最大colspan,例如:
<table>
 <tr>
  <td> 1 </td>
  <td> 2 </td>
  <td> 3 </td>
 </tr>
 <tr>
  <td> 1 </td>
  <td> 2 </td>
 </tr>
 <tr>
  <td> 1 </td>
 </tr>
</table>
应该给3     
已邀请:
        每个表都有一个“ 1”数组,每行有一个“ 2”数组。然后,只需要找到一个最大值即可。
function calculateCells(){
    var table = document.getElementById(\"table\");
    var max = 0;
    for(var i=0;i<table.rows.length;i++) {
        if(max < table.rows[i].cells.length)
            max = table.rows[i].cells.length;
    }
    return max;
}
    
         用\“ getElementsByTagName()\”查找每个
<tr>
对于每个
<tr>
,类似地找到每个ѭ​​6ѭ 计算
<td>
个元素,然后遍历并为每个
<td>
添加\“ colspan-1 \”,并带有\“ colspan \”属性 保持所有行的最大计数。     
        有关示例,请参见此jsFiddle。根据您的要求,它采用纯JavaScript:
var table = document.getElementById(\"myTable\");
var max = 0;

for (var i = 0, iLen = table.rows.length; i < iLen; i++) {
  var temp = 0;
  var cells = table.rows[i].cells;

  for (var j = 0, jLen = cells.length; j < jLen; j++) {
    // This is very important. If you just take length you\'ll get the
    // the wrong answer when colspan exists
    temp += cells[j].colSpan;
  }

  if (temp > max) {
    max = temp;
  }
}

alert(max);
    
        有关jQuery版本,请参见此小提琴。它计算每个ѭ11中的ѭ10个元素的数量,并每次检查是否遇到更多的元素。
max
变量存储找到的当前最大列数:
var max = 0;
$(\"tr\").each(function() {
   var count = $(this).find(\"td\").length;
    if(count > max) max = count;
});
alert(max);
    

要回复问题请先登录注册