Hiding columns in table JavaScript

后端 未结 3 1627
离开以前
离开以前 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:15

    You could use children and check their tagName to make sure they're td's. Something like this:

    function show_hide_column(col_no, do_show) {
        var tbl = document.getElementById('id_of_table');
        var rows = tbl.getElementsByTagName('tr');
    
        for (var row = 0; row < rows.length; row++) {
            var cols = rows[row].children;
            if (col_no >= 0 && col_no < cols.length) {
                var cell = cols[col_no];
                if (cell.tagName == 'TD') cell.style.display = do_show ? 'block' : 'none';
            }
        }
    }
    

    Edit: Here's a working example: http://jsfiddle.net/3DjhL/2/.

    Edit: In fact, I've just remembered the rows and cols properties, which make it even simpler. See http://jsfiddle.net/3DjhL/4/ to see it in action.

    function show_hide_column(col_no, do_show) {
        var rows = document.getElementById('id_of_table').rows;
    
        for (var row = 0; row < rows.length; row++) {
            var cols = rows[row].cells;
            if (col_no >= 0 && col_no < cols.length) {
                cols[col_no].style.display = do_show ? '' : 'none';
            }
        }
    }
    

    Oh, and if you think the column numbers should start at 1 (which they don't), you'll have to offset that somewhere. For example at the top of show_hide_column():

    col_no = col_no - 1;
    

提交回复
热议问题