Hiding columns in table JavaScript

后端 未结 3 1621
离开以前
离开以前 2020-12-10 12:01

This script stops working the moment I add a table inside a table, so how to get it worked? I don\'t need any jQuery solutions, I want pure JavaScript. Here\'s my sc

3条回答
  •  死守一世寂寞
    2020-12-10 12:39

    I had a situation where it would have been a very big hassle to modify every single TD value and add the appropriate class name so I could toggle it. As a result I wrote some JavaScript to do that automatically. Please see the following code.

      tbl = document.getElementById("Mytable")
      classes = getClasses(tbl.rows[0]);
      setClasses(tbl, classes);
      toggleCol("col0");
      toggleCol("col1");
    
    
    
    function getClasses(row){
        var cn = 0;
        var classes = new Array();
        for(x=0; x < row.cells.length; x++){
            var cell = row.cells[x];
            var c = new Column(cell.textContent.trim(), cell.offsetLeft, cell.offsetLeft + cell.offsetWidth, x);
            classes[x]= c;
        }
        return classes;
    }
    
    function Column(name, left, right, cols) {
        this.name = name;
        this.left = left;
        this.right = right;
        this.cols = cols;
    }
    
    function setClasses(table, classes){
        var rowSpans = new Array();
        for(x=0; x < table.rows.length; x++){
            var row = table.rows[x]; 
            for(y=0; y < row.cells.length; y++){
                var cell = row.cells[y];
                for(z=0; z < classes.length; z++){
                  if(cell.offsetLeft >= classes[z].left && cell.offsetLeft <= classes[z].right){
                    cell.className = "col" + classes[z].cols;
                  }
                }
            }    
        }
    }
    
    function toggleCol(name){ 
      var cols = document.getElementsByClassName(name); 
      for(x=0; x < cols.length; x++){ 
        cols[x].style.display= (cols[x].style.display == 'none') ? '' : 'none'; 
       }
    }
    

    In my example I take a look at the first row to set the top level header (In my example I had several who had colspans). It uses the offsetLeft and offsetWidth to determine the range of the top header (which in my cases has sub headers), so that all sub-columns would toggle with its parent.

    Based on these values setClasses sets the appropriate classes to all the elements.

    In my example I then toggle "col0" and "col1", so they would be invisible (Running the function again would make them visible again).

提交回复
热议问题