开发者

how to check with javascript how many columns given html table has?

That is how is the maximum colspan, for example:

<table>
 <tr>
  <td&开发者_StackOverflow社区gt; 1 </td>
  <td> 2 </td>
  <td> 3 </td>
 </tr>
 <tr>
  <td> 1 </td>
  <td> 2 </td>
 </tr>
 <tr>
  <td> 1 </td>
 </tr>
</table>

should give 3


  1. Find each <tr> with "getElementsByTagName()"
  2. For each <tr>, find each <td> similarly
  3. Count the <td> elements, then iterate through and add "colspan - 1" for each <td> with a "colspan" attribute
  4. Maintain a maximum count over all rows.


See this jsFiddle for an example. As you requested, it's in plain 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);


Each table has a rows array, and each row has a cells array. Then it's just a matter a finding the maximum.

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


See this fiddle for a jQuery version. It counts the number of td elements in each tr and checks each time to see if a greater number has been encountered. The max variable stores the current maximum number of columns found:

var max = 0;
$("tr").each(function() {
   var count = $(this).find("td").length;
    if(count > max) max = count;
});
alert(max);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜